Created
December 22, 2011 10:01
-
-
Save ashmoran/1509779 to your computer and use it in GitHub Desktop.
Building CanCan abilities incrementally (most edits are minor, I removed direct use of Class at some point)
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
require 'spec_helper' | |
require 'spec/environments/mongoid' | |
require_unless_rails_loaded 'app/models/ability' | |
describe Ability do | |
let(:user) { mock(User) } | |
describe ".build" do | |
let(:ability_builder_1) { | |
Ability::AbilityBuilder.new do | |
def build | |
can(:throw, Object) | |
end | |
end | |
} | |
let(:ability_builder_2) { | |
Ability::AbilityBuilder.new do | |
def build | |
can(:worship, Object) | |
cannot(:throw, Object) | |
end | |
end | |
} | |
let(:ability_builder_with_user) { | |
Ability::AbilityBuilder.new do | |
def build | |
if user.admin? | |
can(:administrate, Object) | |
else | |
can(:beg_for, Object) | |
end | |
end | |
end | |
} | |
context "no abilities" do | |
subject { Ability.build(user) } | |
describe "#can?" do | |
it "exists" do | |
subject.can?(:eat, Object).should be_false | |
end | |
end | |
end | |
context "an ability builder" do | |
subject { Ability.build(user, ability_builder_1) } | |
describe "#can?" do | |
it "is driven by the ability builders" do | |
subject.should be_able_to(:throw, Object) | |
end | |
end | |
end | |
context "two ability builders" do | |
subject { Ability.build(user, ability_builder_1, ability_builder_2) } | |
describe "#can?" do | |
it "uses all ability builders" do | |
subject.should be_able_to(:worship, Object) | |
end | |
it "uses ability builders in the order they were provided" do | |
subject.should_not be_able_to(:throw, Object) | |
end | |
end | |
end | |
context "an ability builder that depends on the user" do | |
subject { Ability.build(user, ability_builder_with_user) } | |
context "when the user is an administrator" do | |
before(:each) do | |
user.stub(admin?: true) | |
end | |
it "uses the user" do | |
subject.should be_able_to(:administrate, Object) | |
subject.should_not be_able_to(:beg_for, Object) | |
end | |
end | |
context "when the user is not an administrator" do | |
before(:each) do | |
user.stub(admin?: false) | |
end | |
it "uses the user" do | |
subject.should be_able_to(:beg_for, Object) | |
subject.should_not be_able_to(:administrate, Object) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment