Skip to content

Instantly share code, notes, and snippets.

@penguinpowernz
Created May 29, 2014 02:56
Show Gist options
  • Save penguinpowernz/d8904c657d09d25e1703 to your computer and use it in GitHub Desktop.
Save penguinpowernz/d8904c657d09d25e1703 to your computer and use it in GitHub Desktop.
Custom permit matcher for matching authorizer actions using a nice syntax (like Pundit)

RSpec permit matcher for Authorizer classes

I use authorizer classes in my app that I learned about from a blog post by @sethvargo.

This is a custom rspec matcher for Authorizer classes gleaned from this post by @thunderboltlabs that allows you to use permit in your Rspec tests.

Save the gist below to `` and add the following line to your spec_helper.rb file (if you haven't already).

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

Then you can use it in tests like this:

describe CustomerStaffAuthorizer do
  subject(:authorizer) { CustomerStaffAuthorizer.new(user, staff) }
  let(:customer)       { create :customer }
  let(:competitor)     { create :customer }

  context "as a competitor" do 
    let(:staff)       { customer.staff.first }
    let(:user)        { competitor.staff.first }

    it "should not permit reset password" do
      expect(authorizer).to_not permit(:reset_password)
    end
  end
end

Easy! And clear!

Sources

# spec/support/permit_matcher.rb
RSpec::Matchers.define :permit do |action|
match do |authorizer|
authorizer.public_send("#{action}?")
end
description do
"permit the action #{action}"
end
# for when we upgrade to RSpec 3
# failure_message do |authorizer|
# "#{authorizer.class} does not permit #{action} on #{authorizer.record} for #{authorizer.user.inspect}."
# end
# failure_message_when_negated do |authorizer|
# "#{authorizer.class} does not forbid #{action} on #{authorizer.record} for #{authorizer.user.inspect}."
# end
failure_message_for_should do |authorizer|
"#{authorizer.class} does not permit #{action} on #{authorizer.record} for #{authorizer.user.inspect}."
end
failure_message_for_should_not do |authorizer|
"#{authorizer.class} does not forbid #{action} on #{authorizer.record} for #{authorizer.user.inspect}."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment