Skip to content

Instantly share code, notes, and snippets.

@crwang
Last active June 1, 2016 18:12
Show Gist options
  • Save crwang/8f669777082b30ef4a06 to your computer and use it in GitHub Desktop.
Save crwang/8f669777082b30ef4a06 to your computer and use it in GitHub Desktop.
Rspec Pundit Matcher
#spec/support/matchers/pundit_matcher.rb
#borrowed from http://thunderboltlabs.com/blog/2013/03/27/testing-pundit-policies-with-rspec/
#using permit_authorization instead of permit so we don't clash with shoulda's permit
RSpec::Matchers.define :allow_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
# spec/spec_helper.rb
# Add this line to the existing file before the end
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
# spec/policies/user_policy_spec.rb
require 'spec_helper'
describe UserPolicy do
subject { UserPolicy.new(user, target_user) }
let(:target_user) { FactoryGirl.create(:user) }
context "for a visitor" do
let(:user) { nil }
it { should_not allow_action(:show) }
it { should_not allow_action(:create) }
it { should_not allow_action(:new) }
it { should_not allow_action(:update) }
it { should_not allow_action(:edit) }
it { should_not allow_action(:destroy) }
end
context "for a normal user" do
let(:user) { User.new }
it { should_not allow_action(:show) }
it { should_not allow_action(:create) }
it { should_not allow_action(:new) }
it { should_not allow_action(:update) }
it { should_not allow_action(:edit) }
it { should_not allow_action(:destroy) }
end
context "for an admin" do
let(:user) {
u = User.new
u.add_role :admin
return u
}
it { should allow_action(:show) }
it { should allow_action(:create) }
it { should allow_action(:new) }
it { should allow_action(:update) }
it { should allow_action(:edit) }
it { should allow_action(:destroy) }
end
after(:all) do
DatabaseCleaner.clean_with(:truncation)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment