Skip to content

Instantly share code, notes, and snippets.

@ajvargo
Created May 10, 2011 04:41
Show Gist options
  • Save ajvargo/963908 to your computer and use it in GitHub Desktop.
Save ajvargo/963908 to your computer and use it in GitHub Desktop.
Custom Matcher for Declarative Authorization authorization specs with RSpec
# in spec/spec_helper.rb, add this to make it work:
# require 'support/be_allowed_to'
# RSpec.configure |config|
# config.include(BeAllowedToMatcher)
# end
#
# allows: some_user.should be_allowed_to(:edit, thing)
# some_user.should be_allowed_to(:edit, :things)
# some_user.should be_allowed_to(:edit, thing, in_this_context)
# along with the should_not variants
module BeAllowedToMatcher
class BeAllowedTo
def initialize(privilege, object_or_context, context)
@privilege = privilege
@object_or_context = object_or_context
@context = context
end
def matches?(user)
@user = user
Authorization.current_user = user
options = { }
options[@object_or_context.is_a?(Symbol) ? :context : :object] = @object_or_context
options[:context] = @context if @context
Authorization::Engine.instance.permit? @privilege, options
end
def failure_message_for_should
"expected #{@user.class}: #{@user.role} to be able to #{message}"
end
def failure_message_for_should_not
"expected #{@user.class}: #{@user.role} NOT to be able to #{message}"
end
private
def message
txt = "'#{@privilege}' "
txt += @object_or_context.is_a?(Symbol) ? @object_or_context.to_s : "of #{@object_or_context.class} instance"
txt += " in context #{@context}" if @context
txt
end
end
def be_allowed_to(privilege, object_or_context, context=nil)
BeAllowedTo.new(privilege, object_or_context, context)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment