如何使用RSpec测试CanCan的权限?

5
我第一次测试CanCan的能力,但遇到了问题。即使我在can: invite_to块内返回false / true,我仍然无法通过规格测试。我是不是忘记使用CanCan匹配器? 还是存根? 或者在CanCan中定义能力?还有其他需要注意的地方吗?
ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    can :invite_to, Network do |network|
      network.allows_invitations? && (user.admin? || user.can_send_invitations_for?(network))
    end
  end
end

ability_spec.rb

require 'cancan'
require 'cancan/matchers'
require_relative '../../app/models/ability.rb'

class Network; end;

describe Ability do
  let(:ability) { Ability.new(@user) }

  describe "#invite_to, Network" do
    context "when network level invitations are enabled" do
      let(:network) { stub(allows_invitations?: true) }

      it "allows an admin" do
        @user = stub(admin?: true)
        ability.should be_able_to(:invite_to, network)
      end

      it "allows a member if the member's invitation privileges are enabled" do
        @user = stub(admin?: false, can_send_invitations_for?: true)
        ability.should be_able_to(:invite_to, network)
      end

      it "denies a member if the member's invitation privileges are disabled" do
        @user = stub(admin?: false, can_send_invitations_for?: false)
        ability.should_not be_able_to(:invite_to, network)
      end
    end
  end
end

故障

  1) Ability#invite_to, Network when network level invitations are enabled allows an admin
     Failure/Error: ability.should be_able_to(:invite_to, network)
       expected to be able to :invite_to #<RSpec::Mocks::Mock:0x3fe3ed90444c @name=nil>
     # ./spec/models/ability_spec.rb:16:in `block (4 levels) in <top (required)>'

  2) Ability#invite_to, Network when network level invitations are enabled allows a member if the member's invitation privileges are enabled
     Failure/Error: ability.should be_able_to(:invite_to, network)
       expected to be able to :invite_to #<RSpec::Mocks::Mock:0x3fe3edc27408 @name=nil>
     # ./spec/models/ability_spec.rb:21:in `block (4 levels) in <top (required)>'
1个回答

5
  let(:network) do 
    n = Network.new
    n.stub!(:allows_invitations? => true)
    n
  end

如果按照您编写的代码运行,那么 Can 块内部的代码将永远不会被执行。您对 stub 的调用返回了一个 RSpec::Mocks::Mock 类的对象;为了让 CanCan 应用规则,它必须是 Network 类的对象。

非常好的发现。我刚刚在文档中读到了关于当给定一个类而不是实例时它会跳过该块的部分。虽然我没有想到,但还是谢谢你。 - Eric M.

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