如何为应该在Pundit授权机制之后失败的请求编写请求RSpec?

时间:2018-12-07 15:17:50

标签: ruby-on-rails testing rspec rspec-rails pundit

我设置了Pundit来保护一堆请求路径,并且一切正常。特别是,如果我用PATCH请求命中/api/users/:id并传递了相关参数,那么如果未通过身份验证,则会得到403。然后我写了这个规范

context 'When logged out' do
  describe 'user update' do
    before(:each) do
      @new_user = FactoryBot.create(:user, password: 'testpassword')
    end

    it 'fails with PATCH' do
      patch "/api/users/#{@new_user.id}", params: { given_name: 'Testing Alice' }
      expect(response).to have_http_status(:forbidden)
    end
  end
end

但是当我运行rspec时,出现以下错误:

  1) When logged out user update fails with PATCH
     Failure/Error: authorize @user

     Pundit::NotAuthorizedError:
       not allowed to update? this #<User id: 24, email: "nolanschinner@schuster.net", given_name: "Deja", family_name: "Schmeler", role: "USER", password_digest: "$2a$04$3lhKjBj2DfLymYnTfhDZV.IrlhPPxsPHIe.hI0lHdb1...", created_at: "2018-12-07 15:08:00", updated_at: "2018-12-07 15:08:00", verification_token: nil, email_verified: false, gender: nil>
     # /Users/morpheu5/.rvm/gems/ruby-2.5.1/gems/pundit-2.0.0/lib/pundit.rb:209:in `authorize'
     # ./app/controllers/api/v1/users_controller.rb:55:in `update'
     # ...

正在测试的方法是right here

据我所知,Pundit引发了异常,这使rspec陷入了绝望。如何编写此测试以使其真正起作用?

1 个答案:

答案 0 :(得分:0)

这个主题有点老了,但对于那些仍在寻找答案的人,你应该写一些类似的东西:

context 'When logged out' do
  describe 'user update' do
    before(:each) do
      @new_user = FactoryBot.create(:user, password: 'testpassword')
    end

    it 'fails with PATCH' do
      expect{patch "/api/users/#{@new_user.id}", params: { given_name: 'Testing Alice' }}.to raise_error(Pundit::NotAuthorizedError)
    end
  end
end