使用RSpec测试嵌套的CanCan权限

3

我花了一些时间研究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
你确定你可以在块内调用第二个 can 吗?我在 Defining Abilities with Blocks 维基页面上没有看到任何这样的例子。请记住,直到权限被检查之前,该块不会被评估。 - Jared Beck
1个回答

0

我们需要更多关于您的模型和“can_read?”条件的具体信息,才能正确回答这个问题。我不确定您的隶属关系模型与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} }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接