2010-12-20 164 views
2

我在项目中使用RSpec和CanCan。我正在测试与Ability类有关的规范中的权限逻辑。对于控制器,我真的只是想确保我正在进行授权检查。我设置了一个控制器宏,但它似乎没有正常工作。RSpec和CanCan控制器测试

所以真的,我有两个问题。一,是测试我的控制器的权限逻辑足够的策略(或者我应该更多地测试控制器授权逻辑)?

二,有没有人看到我做错了,使这不工作?

#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 

我从RSpec中得到的输出如下

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' 

我真的不知道我应该检查哪些方法当我打电话!授权控制器(或者是通过自动调用load_and_authorize_resource)

回答

2

should_receive是对未来发生的事情的期望。反向这两行:

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

所以你有这样的:

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