如何使用RSpec正确测试CanCan功能

Eri*_* M. 3 ruby rspec ruby-on-rails cancan ruby-on-rails-3

我是第一次测试CanCan功能,但感到很沮丧。我丢失了一些东西...即使我在can:invite_to块内返回false / true,我仍然没有通过规格。我是否缺少使用CanCan匹配器?还是存根?或在CanCan中定义功能?

我有什么想念的吗?

能力

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
Run Code Online (Sandbox Code Playgroud)

Capacity_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
Run Code Online (Sandbox Code Playgroud)

失败的

  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)>'
Run Code Online (Sandbox Code Playgroud)

小智 5

  let(:network) do 
    n = Network.new
    n.stub!(:allows_invitations? => true)
    n
  end
Run Code Online (Sandbox Code Playgroud)

如果您在编写代码时运行该代码,则Can块内的代码将永远无法到达。您对存根的调用将返回RSpec :: Mocks :: Mock类的对象;它必须属于Network类,CanCan才能应用规则。