How to Properly Test Cancan Abilities with Rspec

How do I properly test CanCan abilities with RSpec

  let(:network) do 
n = Network.new
n.stub!(:allows_invitations? => true)
n
end

If you run the code as you wrote it, the code inside the Can block is never reached. Your call to stub returns an object of class RSpec::Mocks::Mock; it must be of class Network for CanCan to apply the rule.

Testing cancancan abilities with rspec

First of all, I advise you to use an explicit subject for @ability so you can use the one-liner syntax like in the example below.

describe Role do
subject(:ability){ Ability.new(user) }
let(:user){ FactoryGirl.build(:user, roles: [role]) }

context "when is a manager" do
let(:role){ FactoryGirl.build(:manager_role) }

it{ is_expected.not_to be_able_to(:create, Question.new) }
it{ is_expected.not_to be_able_to(:read, Question.new) }
it{ is_expected.not_to be_able_to(:update, Question.new) }
it{ is_expected.not_to be_able_to(:destroy, Question.new) }
end
end

Updated after your comment

But you can also summarize all this 4 expectations to simply

%i[create read update destroy].each do |role|
it{ is_expected.not_to be_able_to(role, Question.new) }
end

how to write rspec for ability using cancancan

Based on the limited information you have provided, I'm going to share a sample spec which tests abilities.

describe "User" do
describe "Check for Abilities" do
let(:user) { FactoryGirl.create(:user) }

describe "What User can do" do
it { should be_able_to(:create, Post.new) }
it { should be_able_to(:update, Post.new) }
end
end
end

What I have provided at the top was a Sample, using which you have to build upon it. My updated answer

require "cancan/matchers"

describe "User" do
describe "abilities" do
user = User.create!
ability = Ability.new(user)
expect(ability).to be_able_to(:create, Post.new)
expect(ability).to_not be_able_to(:destroy, Post.new)
end
end

Testing CanCanCan ability definition

expect(subject).to_not be_able_to(:crud, User) 

You are referencing User model, not instance there. Use User.new or another persisted User instance.

Testing abilities in CanCan with new Rspec syntax

You can use the should_not syntax in your shortened version:

it { should_not be_able_to :delete, User.new }

or alternatively, with RSpec 3's synonyms:

it { is_expected.not_to be_able_to :delete, User.new }

Testing cancan abilities with Factory Girl

Ok. Very embarrassing. I missed something simple - not putting this inside a proper it call.

Only consolation is that I'm not the first.



Related Topics



Leave a reply



Submit