Skip to content

Instantly share code, notes, and snippets.

@justincampbell
Created February 9, 2012 20:25
Show Gist options
  • Save justincampbell/1782830 to your computer and use it in GitHub Desktop.
Save justincampbell/1782830 to your computer and use it in GitHub Desktop.
CanCan Ability Spec
require 'spec_helper'
describe Ability do
let(:admin_user) { mock AdminUser }
it { Ability.should include(CanCan::Ability) }
it { Ability.should respond_to(:new).with(1).argument }
context "admin" do
before :each do
admin_user.stub!(:role).and_return("admin")
end
it "can manage all" do
Ability.any_instance.should_receive(:can).with(:manage, :all)
Ability.new admin_user
end
end
context "editor" do
before :each do
admin_user.stub!(:role).and_return("editor")
end
it "can not manage all" do
Ability.any_instance.should_not_receive(:can).with(:manage, :all)
Ability.new admin_user
end
it "can create and edit models" do
[Thing, Widget].each do |model|
Ability.any_instance.should_receive(:can).with([:read, :update], model)
end
Ability.new admin_user
end
end
end
@atomical
Copy link

I get this output when I try to use should_receive:

undefined method `should_receive' for Ability:Class (NoMethodError)

@justincampbell
Copy link
Author

@atomical It sounds like you don't have rspec loaded correctly

@atomical
Copy link

At the top:
require 'spec_helper'
require "cancan/matchers"

Would it be a matcher?

@justincampbell
Copy link
Author

.should_receive is a method from rspec-expectations.

Honestly the code above is probably not the best way to do this. Take a look here: https://github.com/ryanb/cancan/wiki/Testing-Abilities

@atomical
Copy link

atomical commented Mar 13, 2012 via email

@justincampbell
Copy link
Author

Updated the gist with our latest code. I think .any_instance will solve the problem you were having. Hope this helps.

@atomical
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment