此规范中放置和update_attributes之间的区别



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

# 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应该按照失败测试中的调用,调用我的控制器的 before 过滤器:

# 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吗?为什么不放?

update_attributes不是

请求,而是一种模型方法 - 过滤器在请求上下文之外毫无意义。

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

相关内容

  • 没有找到相关文章

最新更新