2012-02-24 82 views
3

我花了一點時間挖掘CanCan以獲取嵌套的資源。它在瀏覽器中按預期工作,但我無法獲得相關的技能規格。我猜它與CanCan處理嵌套路線的方式有關。有關如何正確測試失敗能力的任何建議(標記如下)?謝謝。使用RSpec測試嵌套的CanCan功能

describe "Network" do 
    let(:network) { Network.new } 

    describe "#read" do 
     it "allows a user that meets the can_read? requirements" do 
     NetworkManagementPolicy.stub_chain(:new, :can_read?).and_return(true) 
     ability_for(user).should be_able_to(:read, network) 
     end 

     it "denies a user that does not meet the can_read? requirements" do 
     NetworkManagementPolicy.stub_chain(:new, :can_read?).and_return(false) 
     ability_for(user).should_not be_able_to(:read, network) 
     end 

     describe "Affiliation" do 
     let(:affiliation) { Affiliation.new } 

     describe "#manage" do 
      it "allows a user that meets the can_modify? requirements" do 
      # NOTE: Not sure why this is failing; Something to do with how 
      # CanCan handles nested resources? 
      # 
      # NetworkManagementPolicy.stub_chain(:new, :can_modify?).and_return(true) 
      # ability_for(user).should be_able_to(:manage, affiliation) 
      end 

      it "denies a user that does not meet the can_modify? requirements" do 
      NetworkManagementPolicy.stub_chain(:new, :can_modify?).and_return(false) 
      ability_for(user).should_not be_able_to(:manage, affiliation) 
      end 
     end 
     end 
    end 
    end 

能力類定義了以下與閱讀網絡和管理從屬關係相關的內容。 NetworkManagementPolicy類根據特定條件返回true/false,並按預期工作。即使刪除對這個類的調用並且很難返回true/false,我也無法獲得能力規格的通過。

can :read, Network do |network| 
    can :manage, Affiliation do |affiliation| 
     NetworkManagementPolicy.new(network).can_modify?(current_user) 
    end 

    NetworkManagementPolicy.new(network).can_read?(current_user) 
    end 
+1

你確定你可以調用塊內的第二個'can'嗎?我在[定義阻止能力](https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks)wiki頁面上看不到任何此類示例。請記住,只有在檢查權限之後纔會評估該塊。 – 2013-02-15 03:47:43

回答

0

我們需要關於您的模型和「can_read?」的更多細節。條件來正確回答這個問題。我不確定您的聯屬模式如何與NetworkManagementPolicy或Network關聯。

但是,考慮到網絡has_many network_management_polices,並且每個聯盟都通過標準軌道慣例附加到用戶和網絡,這應該讓你感動。

class NetworkManagementPolicyController < ApplicationController 
    load_and_authorize_resource :network 
    load_and_authorize_resource :network_management_policy, through: :network 
end 

can :manage, NetworkManagementPolicy, network: { affiliations: { user_id: current_user.id} }