Created
May 10, 2011 04:41
-
-
Save ajvargo/963908 to your computer and use it in GitHub Desktop.
Custom Matcher for Declarative Authorization authorization specs with RSpec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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