代码之家  ›  专栏  ›  技术社区  ›  Morpheu5

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

  •  1
  • Morpheu5  · 技术社区  · 6 年前

    我设置了 Pundit /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

    据我所知,权威人士提出了一个例外,这让rspec陷入了绝望。我该如何编写这个测试以便它实际工作?

    0 回复  |  直到 6 年前
        1
  •  0
  •   Adrian Mole Chris    4 年前

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

    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