How to structure Pundit policy specs
mainTo use Pundit Matchers effectively, follow these structural patterns in your policy specs (e.g., spec/policies/article_policy_spec.rb):
- Declare a Subject: The subject should be a new instance of the policy class, initialized with the
userand therecordbeing authorized.subject { described_class.new(user, article) } - Use
letfor Context: Useletstatements to define theuserand therecord. This allows you to reassign them within different RSpeccontextblocks to test different authorization states. - Implicit Subject: Matchers like
is_expected.to permit_action(:index)implicitly reference the subject defined above.
require 'rails_helper'
RSpec.describe ArticlePolicy do
subject { described_class.new(user, article) }
let(:article) { Article.new }
context 'with visitors' do
let(:user) { nil }
it { is_expected.to permit_only_actions(%i[index show]) }
end
context 'with administrators' do
let(:user) { User.new(administrator: true) }
it { is_expected.to permit_all_actions }
end
end