Ruby 验证是否向不同的对象/类发送了一系列消息
我有一个保存模型并运行后台作业的对象Ruby 验证是否向不同的对象/类发送了一系列消息,ruby,rspec3,Ruby,Rspec3,我有一个保存模型并运行后台作业的对象 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)
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
中时,这一切都很好。
但是,当我添加了后台作业后,规范不再通过,因为现在无法找到没有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
#因此,在第一个规范中,作业无法获取id
谢谢考虑到perform
方法中的代码,在没有ID的情况下无法找到帐户的错误实际上非常有用
评论中提到了这个问题,但我将进一步阐述
您正在使用@account.save
(我假设@account
是一个ActiveRecord
对象),根据定义,它在运行()
您可能希望改用它,因为它将引发ActiveRecord::RecordInvalid
错误并停止执行,而不是触发您前面提到的错误。(扔出一个绑定。撬动进入该方法,并在尝试调用.id
时注意@account
是什么)
当您更改为保存时代码>您可以为保存可能失败(缺少属性等)的情况添加测试。可能看起来像这样
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有任何问题/需要更多帮助,请告诉我您是否有验证@account.save
实际返回true
的规范?我猜@account.save
返回false
aka该帐户无效,未保存,因此未分配id
。我相信@spickermann是正确的。我添加了一个答案来解释save代码>和保存
。希望这能帮助你,谢谢你的回复。实际上,我不明白您是否建议我的帐户未保存或已保存,但save
没有返回我想要的内容。请阅读我链接的文档。如果save
返回false,则记录未保存到数据库(因此缺少id)
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