【问题标题】:Verify a sequence of messages are sent to different objects/classes验证将一系列消息发送到不同的对象/类
【发布时间】: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 之间的区别。希望这对您有所帮助

标签: ruby rspec3


【解决方案1】:

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

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

您正在使用@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 有任何疑问/需要更多帮助,请告诉我

【讨论】:

  • 感谢您的回复。我真的不明白你是在暗示我的帐户没有保存还是保存了但save 没有返回我想要的。
  • 请阅读我链接的文档。如果save 返回 false 则您的记录没有保存到数据库中(因此缺少 id)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 2013-06-05
  • 2017-06-12
  • 2022-08-16
  • 2020-12-25
  • 1970-01-01
  • 2013-02-02
相关资源
最近更新 更多