Created
February 16, 2015 23:28
-
-
Save supairish/264433809a992c342579 to your computer and use it in GitHub Desktop.
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
# e.g.: | |
# @user.should have_ability(:create, for: Post.new) | |
# @user.should have_ability([:create, :read], for: Post.new) | |
# @user.should have_ability({create: true, read: false, update: false, destroy: true}, for: Post.new) | |
RSpec::Matchers.define :have_ability do |ability_hash, options = {}| | |
match do |user| | |
ability = Ability.new(user) | |
target = options[:for] | |
@ability_result = {} | |
ability_hash = {ability_hash => true} if ability_hash.is_a? Symbol # e.g.: :create => {:create => true} | |
ability_hash = ability_hash.inject({}){|_, i| _.merge({i=>true}) } if ability_hash.is_a? Array # e.g.: [:create, :read] => {:create=>true, :read=>true} | |
ability_hash.each do |action, true_or_false| | |
@ability_result[action] = ability.can?(action, target) | |
end | |
!ability_hash.diff(@ability_result).any? | |
end | |
failure_message_for_should do |user| | |
ability_hash,options = expected | |
ability_hash = {ability_hash => true} if ability_hash.is_a? Symbol # e.g.: :create | |
ability_hash = ability_hash.inject({}){|_, i| _.merge({i=>true}) } if ability_hash.is_a? Array # e.g.: [:create, :read] => {:create=>true, :read=>true} | |
target = options[:for] | |
message = "expected User:#{user} to have ability:#{ability_hash} for #{target}, but actual result is #{@ability_result}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment