Rails: Check Pundit authorization in RSpec
Pundit provide two helper methods to help you ensure the actions are authorized/scoped: verify_authorized
and verify_policy_scoped
. They are meant to be used in an after_action
hook.
As the check is made after the action, I see no point of using it in production, so I use it in RSpec:
# rails_helper.rb
# ...
config.before(:suite) do
FactoryBot.create :user, :known
ApplicationController.send(:after_action, :verify_authorized, {except: [:index]})
ApplicationController.send(:after_action, :verify_policy_scoped, {only: [:index]})
end
# ...
This way, it's still checked during all the tests using controllers.