我有一个类方法,它只遍历一些记录并在每条记录上执行一个实例方法。我正在尝试为类方法编写一个简单的测试,以确保它将实例方法发送到每条记录。
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
但我真的不喜欢那样,想知道为什么我的第一次尝试不起作用。