gpt4 book ai didi

ruby-on-rails - Rspec should_receive 在一个没有行为的实例上

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:35 26 4
gpt4 key购买 nike

我有一个类方法,它只是遍历一些记录并在每条记录上执行一个实例方法。我正在尝试为类方法编写一个简单的测试,以确保它将实例方法发送到每条记录。

it "fires any pending alarms" do
pending = create :alarm, :pending
other_pending = create :alarm, :pending

# sanity check
Alarm.pending.sort.should eq [pending, other_pending].sort

pending.should_receive(:fire)
other_pending.should_receive(:fire)

Alarm.fire_pending
end

报警.rb

class Alarm < ActiveRecord::Base
scope :pending, where(pending: true)

def self.fire_pending
self.pending.each do |alarm|
alarm.fire
end
end
end

但是我在 should_receive 期望上收到错误:

 Failure/Error: pending.should_receive(:fire)
(#<Alarm:0x007fcc96334310>).fire(any args)
expected: 1 time
received: 0 times

我之前成功使用过这个期望。恐怕我遗漏了一些明显的东西。

编辑

我现在已经解决了这个问题:

it "fires any pending alarms" do
pending = create :alarm, :pending
other_pending = create :alarm, :pending

pending_alarms = Alarm.pending
pending_alarms.sort.should eq [pending, other_pending].sort

Alarm.stub(:pending) { pending_alarms }
pending_alarms.first.should_receive(:fire)
pending_alarms.last.should_receive(:fire)

Alarm.fire_pending
end

但我不太喜欢那样,想知道为什么我的第一次尝试不起作用。

最佳答案

Alarm.pending 返回的对象与示例中创建的实例不同。您可以通过更改看到这一点:

pending_alarms.sort.should eq [pending, other_pending].sort

到:

# the eq matcher uses == (object equivalence)
# the equal matcher uses equals? (object identity)
pending_alarms.sort.tap do |sorted|
sorted[0].should eq pending # passes
sorted[1].should eq other_pending # passes
sorted[0].should equal pending # fails
sorted[1].should equal other_pending # fails
end

这是使用(邪恶的)any_instance 的好例子:

it "fires any pending alarms" do
pending = create :alarm, :pending
Pending.any_instance.should_receive(:fire)
Alarm.fire_pending
end

关于ruby-on-rails - Rspec should_receive 在一个没有行为的实例上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12400555/

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