gpt4 book ai didi

ruby - 验证一系列消息被发送到不同的对象/类

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

我有一个对象可以保存模型并运行后台作业。

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。

谢谢

最佳答案

Couldn't find Account without an ID 错误实际上非常有用,考虑到您在 perform 方法中的代码。

评论中提到了这个问题,但我会进一步详细说明。

您正在使用 @account.save(我假设 @account 是一个 ActiveRecord 对象),根据定义它会返回 true/false 运行时 ( see documentation )

您可能想要使用 save!相反,因为它会引发 ActiveRecord::RecordInvalid 错误并停止执行,而不是触发您之前注意到的错误。 (将 binding.pry 扔到方法中,并注意在尝试调用 .id@account 是什么)

当您更改为 save! 时,您可以为保存可能失败的情况(缺少属性等)添加测试。可能看起来像这样

it 'should raise error when trying to save invalid record' do
# do something to invalidate @account
@account.username = nil
expect { UseCase.perform(@account) }.to raise_error(ActiveRecord::RecordInvalid)
#confirm that no messages were sent
end

希望对您有所帮助! GL,如果您有任何问题/需要更多关于 rspec 的帮助,请告诉我

关于ruby - 验证一系列消息被发送到不同的对象/类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40213428/

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