Search code examples
ruby-on-railsrspeccancan

How to stub load of load_and_authorize_resource in controller ability tests?


I have this in tests:

let(:ability) { Object.new.extend(CanCan::Ability) }

...
describe "GET show" do
  it 'redirects to root if havent read ability' do
    allow(@controller).to receive(:current_ability).and_return(ability)
    ability.cannot :read, Book
    get :show, { id: '1'}
    response.should redirect_to(root_url)
  end
...

in controller I have load_and_authorize_resource from cancan, and when test runs, it tries to fetch record from database with id = 1. I need to test only authorize_resource, not load.

I have fixed it by setting instance variable in controller before calling get:

@controller.instance_variable_set('@author', true) # to skip load_resource

But it is not perfect decision. Is it a better way to skip load and check only authorize_resource in testing abilities in controller with load_and_authorize_resource ?


Solution

  • looks like

    allow_any_instance_of(CanCan::ControllerResource).to receive(:load_resource)
    

    works fine