Skip to content

Instantly share code, notes, and snippets.

@watson
Created September 20, 2011 14:46
Show Gist options
  • Save watson/1229291 to your computer and use it in GitHub Desktop.
Save watson/1229291 to your computer and use it in GitHub Desktop.
CanCan abilities based on attribute value
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
can :manage, Post
cannot [:create, :update, :destroy], Post, :state => 'published'
if user.role?('moderator')
can :manage, Post
end
end
end
require 'spec_helper'
describe Post do
context 'a user with the ability of' do
context 'editor' do
let(:user) { Factory(:editor) }
let(:ability) { Ability.new(user) }
it { ability.should be_able_to(:manage, Post) }
it { ability.should_not be_able_to(:manage, FactoryGirl.build(:post, :state => 'published')) } # => Fails!
it { ability.should be_able_to(:read, FactoryGirl.build(:post, :state => 'published')) }
it { ability.should_not be_able_to(:create, FactoryGirl.build(:post, :state => 'published')) }
it { ability.should_not be_able_to(:update, FactoryGirl.build(:post, :state => 'published')) }
it { ability.should_not be_able_to(:destroy, FactoryGirl.build(:post, :state => 'published')) }
end
context 'moderator' do
let(:user) { Factory(:moderator) }
let(:ability) { Ability.new(user) }
it { ability.should be_able_to(:manage, FactoryGirl.build(:post, :state => 'published')) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment