gpt4 book ai didi

ruby-on-rails - 如何使用 RSpec 正确测试 CanCan 能力

转载 作者:数据小太阳 更新时间:2023-10-29 07:53:54 25 4
gpt4 key购买 nike

我是第一次测试 CanCan 的能力,我被难住了。我遗漏了一些东西……即使我在 can :invite_to block 中返回 false/true,我仍然没有通过规范。我是否缺少使用 CanCan 匹配器?还是 stub ?或在 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 block 内的代码。您对 stub 的调用返回类 RSpec::Mocks::Mock 的对象;它必须属于 Network 类,CanCan 才能应用该规则。

关于ruby-on-rails - 如何使用 RSpec 正确测试 CanCan 能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9306777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com