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

How do I write a request RSpec for a request that should fail behind Pundit's authorization mechanism?

我设置了 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: "alhKjBj2DfLymYnTfhDZV.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 陷入绝望。我如何编写此测试才能使其真正起作用?

这个主题有点老了,但是,对于那些仍在寻找答案的人,你应该这样写:

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