如何为应该在权威人士的授权机制后面失败的请求编写请求 RSpec?



我设置了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'
# ...

正在测试的方法就在这里。

据我所知,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

相关内容

  • 没有找到相关文章

最新更新