Rails Authorization Policies
Implement and test authorization patterns in Rails applications.
Files: SKILL.md · EXAMPLES.md · references/workflow.md
HARD-GATE
ALWAYS test authorization with multiple roles (admin, user, guest)
NEVER rely on presence checks alone — check specific permissions
ALWAYS use policy objects, never inline authorization logic in controllers
Quick Reference
| Gem | Pattern | Best For |
|---|---|---|
| Pundit | Explicit policy classes | Complex per-resource rules |
| CanCanCan | Centralized Ability class | Simple role-based permissions |
Implementation Workflow
- Add gem — add
punditorcancancanto Gemfile and runbundle install - Generate base — run the gem's installer (
rails g pundit:installorrails g cancan:ability) - Define policies/abilities — create policy classes (Pundit) or populate the Ability class (CanCanCan)
- Authorize in controllers — call
authorize @record(Pundit) orauthorize! :action, @record(CanCanCan) in each action - Verify authorization — attempt an unauthorized action in the browser or console and confirm it raises
Pundit::NotAuthorizedErrororCanCan::AccessDeniedas expected - Scope queries — use
policy_scope(Model)oraccessible_by(current_ability)for index actions - Test all roles — write policy specs and request specs covering admin, owner, and guest
See references/workflow.md for the complete implementation guide with additional detail.
Patterns
Pundit
class PostPolicy < ApplicationPolicy
def update?
user.admin? || record.user_id == user.id
end
end
CanCanCan
class Ability
include CanCan::Ability
def initialize(user)
can :update, Post, user_id: user.id
can :manage, :all if user.admin?
end
end
Troubleshooting
| Error | Likely Cause | Fix |
|---|---|---|
Pundit::NotDefinedError |
No policy class found for the record | Create app/policies/model_policy.rb inheriting from ApplicationPolicy |
Pundit::AuthorizationNotPerformedError |
authorize not called in a controller action |
Add authorize @record in the action, or after_action :verify_authorized to catch misses |
CanCan::AccessDenied unexpectedly raised |
Ability rules not matching the current user/role | Inspect current_ability.can?(:action, @record) in the console to debug rule evaluation |
Testing
Cover every role (admin, owner, guest) in both policy specs and request specs.
Inline Policy Spec Example (Pundit)
RSpec.describe PostPolicy do
subject { described_class.new(user, post) }
let(:post) { create(:post, user: owner) }
let(:owner) { create(:user) }
context 'as admin' do
let(:user) { create(:user, :admin) }
it { is_expected.to permit_action(:update) }
end
context 'as owner' do
let(:user) { owner }
it { is_expected.to permit_action(:update) }
end
context 'as guest' do
let(:user) { create(:user) }
it { is_expected.not_to permit_action(:update) }
end
end
See EXAMPLES.md for complete testing examples including:
- Policy specs with
permit_actionmatchers - Request specs with role matrix
- Shared examples for reusable patterns