使用RSpec测试嵌套的CanCan功能

时间:2012-02-24 20:32:37

标签: ruby-on-rails testing rspec cancan

我花了一些时间挖掘CanCan以获得嵌套资源。它在浏览器中按预期工作,但我无法通过相关的能力规范。我猜它与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 个答案:

答案 0 :(得分:0)

我们需要更多关于你的模型和“can_read?”的细节。正确回答这个问题的条件。我不确定您的Affiliation模型与NetworkManagementPolicy或Network的关系。

但是,鉴于网络具有多个network_management_polices并且每个联盟都附加到具有标准rails约定的用户和网络,这应该让您感动。

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} }