Skip to content

Instantly share code, notes, and snippets.

@supairish
Created February 16, 2015 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supairish/264433809a992c342579 to your computer and use it in GitHub Desktop.
Save supairish/264433809a992c342579 to your computer and use it in GitHub Desktop.
# 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