2010-12-20 153 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