skip to content

How do you test Pundit policies and their scopes in a Rails app, with RSpec's permissions DSL or with Minitest?

level: middleimportance: should knowfreq 34%

answer

  1. policies are plain Ruby objects
  2. require pundit/rspec, spec/policies
  3. permissions :update? with permit(user, record)
  4. not_to permit means every listed query denied
  5. scopes: call resolve and compare records

basics

~20 s

Test policies as plain objects: build the policy with a user and a record and assert each predicate. RSpec users can require pundit/rspec for the permissions block and permit matcher; scopes are tested by calling resolve and checking which records come back.

solid answer

~40 s

Because policies are plain Ruby, the core test is `PostPolicy.new(user, post).update?` with each kind of user: guest, author, other member, moderator. With RSpec, `require "pundit/rspec"` adds a `permissions :update?, :edit? do ... end` block and a `permit(user, record)` matcher for specs in `spec/policies`; `expect(PostPolicy).to permit(author, post)` passes only if every listed query is granted, and `not_to permit` only if every one is denied. Using `permit` outside a `permissions` block raises an error since 2.5. Pundit gives no scope DSL, so call `PostPolicy::Scope.new(user, Post).resolve` against fixtures or factories and assert which records it includes. `rails generate pundit:policy` also writes a policy test or spec stub. Keep a request test proving a refused user gets the app's forbidden response.

code

ruby · 23 lines
ruby
# spec/policies/post_policy_spec.rb
require "rails_helper"

RSpec.describe PostPolicy, type: :policy do
  subject { described_class }

  let(:author) { create(:user) }
  let(:other)  { create(:user) }
  let(:post)   { create(:post, author: author) }

  permissions :update?, :edit? do
    it { is_expected.to permit(author, post) }
    it { is_expected.not_to permit(other, post) }
    it { is_expected.not_to permit(nil, post) }
  end

  describe "Scope" do
    it "hides removed posts from other members" do
      removed = create(:post, author: author, removed_at: Time.current)
      expect(PostPolicy::Scope.new(other, Post).resolve).not_to include(removed)
    end
  end
end

go deeper

for a junior

Know that a policy can be tested by building it with a user and a record and asserting the predicate.

for a middle

Use permissions and permit correctly, including the all-or-none semantics, and test Scope#resolve against real records.

for a senior

Cover the user-by-record matrix with unit tests and keep a few request tests for wiring and refusal responses.

for a principal

Set the team's standard for authorization test coverage so rule changes are reviewed through their tests.

## Why policies are easy to test A Pundit policy is a plain Ruby class constructed with `(user, record)`. It does not need a controller, a request or routing, so the most valuable tests are fast unit tests that build the policy directly and call predicates. In a community forum the interesting cases are the **matrix** of users and records: | User | Own post | Someone else's post | Removed post | |---|---|---|---| | guest | n/a | `show?` only | nothing | | member (author) | `update?` | `show?` | `show?` on own only | | moderator | everything | `update?`, `destroy?` | `show?`, `destroy?` | Each cell is one assertion; together they document the rules. ## Minitest Rails apps on Minitest test policies like any class. `rails generate pundit:policy post` hooks into the test framework and writes `test/policies/post_policy_test.rb` with empty `test_scope`, `test_show`, `test_update` methods to fill in: - `assert PostPolicy.new(users(:author), posts(:mine)).update?` - `refute PostPolicy.new(users(:member), posts(:theirs)).update?` - `refute PostPolicy.new(nil, posts(:mine)).update?` for guests ## RSpec and the permissions DSL `require "pundit/rspec"` (in `rails_helper.rb`) adds two things to example groups tagged `type: :policy`, as the generated spec is: 1. **`permissions`**: `permissions :update?, :edit? do ... end` records which queries the examples inside check. 2. **`permit(user, record)`**: a matcher used as `expect(PostPolicy).to permit(author, post)`, usually through `subject { described_class }`. The matcher's semantics are worth knowing precisely: - `to permit` passes only if **every** listed query returns truthy; - `not_to permit` passes only if **every** listed query returns falsy, so grouping `:update?` and `:destroy?` for a member who may update but not destroy fails in both directions; split the block instead; - the failure message names the queries that were or were not granted; - since Pundit 2.5, calling `permit` outside a `permissions` block raises an error that asks whether you forgot the wrapper. `Pundit::RSpec::Matchers.description=` can shorten the generated example descriptions, and the rspec generator writes `spec/policies/post_policy_spec.rb` with pending `permissions` blocks. ## Testing scopes Pundit has no scope DSL; its README says to test scopes like any Ruby class: 1. create records that each user should and should not see; 2. call `PostPolicy::Scope.new(user, Post).resolve`; 3. assert inclusion and exclusion, for example `assert_includes`, `refute_includes`, or RSpec's `contain_exactly`. Testing against the database matters here, because `resolve` is usually SQL: a wrong `or` condition only shows up when the query runs. ## Beyond unit tests Unit tests prove the rules; a few **request tests** prove the wiring: - a member's `PATCH /posts/:id` on someone else's post gets the app's refusal (a redirect with a flash, or 403); - an index request returns only scoped posts; - `verify_authorized` raising in development is not a substitute for these, because it only checks that some call happened. ## Keeping policy tests fast and readable - Prefer in-memory records (`User.new(role: :moderator)`, `Post.new(author: user)`) for predicate tests that do not touch the database; save records only for scope tests. - Name examples after the rule, not the method ("authors may edit their own posts"), so a failure explains which rule broke. - Put the guest case (`nil` user) in every predicate group; it is the case most often forgotten. - Run policy tests in the same suite and CI step as the rest, so a rule change cannot merge without them. ## Pitfalls - Testing only the happy path, so a predicate that returns `true` for everyone passes. - Using `user.admin = true` on a shared fixture and leaking state between tests. - Asserting on a scope's `count` only, which misses a scope that returns the right number of wrong rows.

  • Why does expect(PostPolicy).not_to permit(member, post) inside permissions :update?, :destroy? fail when the member may update?
    The negated matcher passes only when every listed permission is denied. Here `update?` is granted, so it is reported as a violating permission. Split the expectations into separate `permissions :update?` and `permissions :destroy?` blocks so each rule is asserted on its own.
  • Is a controller test enough to cover a policy?
    It proves the wiring for the cases it exercises, but each request test covers one cell of the user-by-record matrix slowly. Unit tests on the policy cover every cell quickly; a few request tests then confirm the controller calls the right policy and turns a refusal into the right response.

  • Policies can only be tested through controller or request tests
  • not_to permit passes when at least one listed query is denied
  • Pundit ships a DSL for testing policy scopes
  • verify_authorized makes policy tests unnecessary
  • The permit matcher works anywhere without a permissions block