John
John

Reputation: 135

RSpec and CanCan Controller Testing

I'm using RSpec and CanCan in a project. I'm testing my permission logic in specs related to the Ability class. For the controllers I really just want to make sure I'm doing an authorization check. I set up a controller macro, but it doesn't seem to be working correctly.

So really I have two questions. One, is the strategy sufficient for testing the permission logic of my controllers (or should I be testing the controller authorization logic more)?

Two, does anyone see what I'm doing wrong to make this not work?

#plan_orders_controller.rb
def approve
  plan_order = PlanOrder.find(params[:id])
  authorize! :update, plan_order
  current_user.approve_plan_order(plan_order)
  redirect_to plan_order_workout_plan_url(plan_order)
end

#controller_macros.rb
def it_should_check_permissions(*actions)
  actions.each do |action|
    it "#{action} action should authorize user to do this action" do
      @plan_order = Factory(:plan_order, :id=>1)
      ability = Object.new
      ability.extend(CanCan::Ability)
      controller.stub!(:current_ability).and_return(ability)        

      get action, :id => 1
      ability.should_receive(:can?)
    end
  end    
end

The output I get from RSpec is the following

 Failure/Error: ability.should_receive(:can?)
 (#<Object:0x00000006d4fa20>).can?(any args)
     expected: 1 time
     received: 0 times
 # ./spec/controllers/controller_macros/controller_macros.rb:27:in `block (2 levels) in it_should_check_permissions'

I'm not really sure which method I should be checking when I call !authorize in the controller (or it is automatically called via load_and_authorize_resource)

Upvotes: 1

Views: 2661

Answers (1)

David Chelimsky
David Chelimsky

Reputation: 9000

should_receive is an expectation of something that happens in the future. Reverse these two lines:

get action, :id => 1
ability.should_receive(:can?)

so you have this:

ability.should_receive(:can?)
get action, :id => 1

Upvotes: 2

Related Questions