繁体   English   中英

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

[英]How do I properly test CanCan abilities with RSpec

我是第一次测试CanCan的能力而且很难过。 我错过了一些东西......即使我在can中返回false / true:invite_to block我仍然没有通过规范。 我错过了使用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)>'
  let(:network) do 
    n = Network.new
    n.stub!(:allows_invitations? => true)
    n
  end

如果在编写代码时运行代码,则永远不会到达Can块中的代码。 你对stub的调用返回一个类RSpec :: Mocks :: Mock的对象; 它必须是CanCan类网络才能应用规则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM