Skip to content

Instantly share code, notes, and snippets.

@michaelachrisco
Created July 9, 2015 15:54
Show Gist options
  • Save michaelachrisco/9841aa2aac1b2d920937 to your computer and use it in GitHub Desktop.
Save michaelachrisco/9841aa2aac1b2d920937 to your computer and use it in GitHub Desktop.
permit_actions on pundit
# spec/support/pundit.rb
RSpec::Matchers.define :permit_action do |action|
match do |policy|
policy.public_send("#{action}?")
end
failure_message do |policy|
"#{policy.class} does not permit #{action} on #{policy.record} \
for #{policy.user.inspect}."
end
failure_message_when_negated do |policy|
"#{policy.class} does not forbid #{action} on #{policy.record} \
for #{policy.user.inspect}."
end
end
def permit_actions(permited_actions)
all_actions = [:index, :show, :new, :create, :edit, :update, :destroy]
permited_actions = all_actions if permited_actions == :all
permited_actions = [] if permited_actions == :none
permited_actions.each do |action|
it "should permit action :#{action}" do
is_expected.to permit_action(action)
end
end
(all_actions - permited_actions). each do |action|
it "should not permit action :#{action}" do
is_expected.not_to permit_action(action)
end
end
end
@michaelachrisco
Copy link
Author

Allows one to do this:

require 'rails_helper'

describe ShipLoadPolicy, :type => :policy do
  let(:load) { build_stubbed(:load) }
  let(:user) do
    u = build_stubbed(:user)
    roles.each { |r| u.add_role r }
    u
  end

  subject { ShipLoadPolicy.new(user, load) }

  context 'when no user' do
    let(:user) { nil }

    permit_actions(:none)
  end

  context 'when user has no roles' do
    let(:roles) { [] }

    permit_actions(:none)
  end

  context 'when user has the accounting role' do
    let(:roles) { [:authenticated, :accounting] }

    permit_actions(:all)
  end

  context 'when user has the dispatch role' do
    let(:roles) { [:authenticated, :dispatch] }

    permit_actions(:all)
  end

  context 'when user has the admin role' do
    let(:roles) { [:authenticated, :admin] }

    permit_actions(:all)
  end

  context 'when user only has the authenticated role' do
    let(:roles) { [:authenticated] }

    permit_actions(:none)
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment