How to write Pundit policy specs
11 March 2022 (Updated 23 April 2022)
On this page
Setup
Add the following to your rails_helper.rb
:
require 'pundit/rspec'
Example spec
Let’s suppose we have a QuotePolicy
that should only allow the owner/creator of a quote to edit the quote. We might write a spec at spec/policies/quote_policy_spec.rb
that looks like this:
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe QuotePolicy, type: :policy do
subject(:policy) { described_class }
let(:user) { create(:user) }
let(:quote) { create(:quote) }
permissions :edit?, :update? do
it 'denies permission if user is not the owner of the quote' do
expect(policy).not_to permit(user, quote)
end
it 'grants permission if user is the owner of the quote' do
quote = create(:quote, user:)
expect(policy).to permit(user, quote)
end
end
permissions :destroy? do
it 'denies permission if user is not the owner of the quote' do
expect(policy).not_to permit(user, quote)
end
it 'grants permission if user is the owner of the quote' do
quote = create(:quote, user: user)
expect(policy).to permit(user, quote)
end
end
end
Tagged:
Rails testing
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment