【发布时间】:2016-10-24 08:03:17
【问题描述】:
我有一个保存模型并运行后台作业的对象。
Class UseCase
...
def self.perform
@account.save
BackgroundJob.perform_later(@account.id)
end
end
在我的规范中,我想分别测试是否发送了两条消息。
我从类似的东西开始
it 'saves the account' do
expect_any_instance_of(Account).to receive(:save)
UseCase.perform(account)
end
当我将帐户保存在 perform 时,这很好用。
但是,当我添加了后台作业时,规范不再通过,因为现在Couldn't find Account without an ID。
如何分别验证(在 RSped 3.5 中)是否发送了两条消息?
更新
it 'runs the job' do
expect(BackgroundJob).to receive(:perform_later).with(instance_of(Fixnum))
UseCase.perform(account)
end
通过,所以我想帐户已正确保存。
但是,当我尝试检查 @account 时
def self.perform
@account.save
byebug
BackgroundJob.perform_later(@account.id)
end
在“保存帐户”中,我得到
(byebug) @account
#<Account id: nil, full_name: "john doe" ...>
在“运行工作”中,我得到
(byebug) @account
#<Account id: 1, full_name: "john doe" ...>
期望使@account 成为test double,因此在第一个规范中,作业无法获取 id。
谢谢
【问题讨论】:
-
您是否有验证
@account.save实际返回true的规范?我猜@account.save返回false也就是帐户无效,没有保存,因此没有分配id。 -
我相信@spickermann 是正确的。我添加了一个答案来解释
save!和save之间的区别。希望这对您有所帮助