Created
September 20, 2011 14:46
-
-
Save watson/1229291 to your computer and use it in GitHub Desktop.
CanCan abilities based on attribute value
This file contains hidden or 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
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 |
This file contains hidden or 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
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