此规范中put和update_attributes之间的差异

时间:2012-06-18 11:02:46

标签: ruby-on-rails rspec put 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,在过滤器之前调用我的控制器:

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

1 个答案:

答案 0 :(得分:1)

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

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