0

愚蠢的提问时间:在以下请求规范中,我尝试确保我的数据库中的第一个用户不能被编辑(除了第一个用户之外的任何人)。

# user is not logged in during these tests

# variant 1 - this passes
describe "first user" do
  let(:first_user){ FactoryGirl.create(:admin) }

  # use put to modify the user
  before { put user_path(first_user, email: 'tst@test.com') }

  # this passes, the response is a redirect
  specify { response.should redirect_to(root_path) }
end

# variant 2 - this test fails
describe "first user" do
  let(:first_user){ FactoryGirl.create(:admin) }

  # this fails, email is updated
  it "can't be updated or edited" do
    expect do
      first_user.update_attributes(email: 'email@test.com')
    end.not_to change(first_user.reload, :email)
  end
end

这两个测试似乎做同样的事情,但一个失败,一个通过。我想我的理解在这里很糟糕。update_attributes 是否应该在失败的测试中调用,调用我的控制器的前置过滤器:

# users_controller.rb
before_filter correct_user, only: [:edit, :update]

private

# pretty messy, but ensures that ordinary users can only
# edit their own accounts, that admin users can
# edit all accounts, except for the first one. 
# I believe it also ensures that the first_user 
# can only be edited by the owner of the first account, i.e. me
# due to the fact that the first condition of the `unless` clause will pass
# if the current_user is the first_user. The complexity is necessary to prevent
# other admins, from being able to edit the first_user.
def correct_user
  @user=User.find(params[:id])
  redirect_to(root_path, only_path: true) unless current_user?(@user) || ( current_user.admin? && !first_user?(@user) )
end

def first_user?(user)
  user==User.first
end

update_attributes 会忽略我的 before_filter 吗?为什么不放?

4

1 回答 1

1

update_attributes 不是请求,而是模型方法——过滤器在请求上下文之外毫无意义。

“put”是一个请求,因此运行过滤器。

于 2012-06-18T11:06:37.520 回答