验证是否将消息序列发送到不同的对象/类

时间:2016-10-24 08:03:18

标签: 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)
  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" ...>

期望值@accounttest double所以在第一个规范中作业无法获取ID。

由于

1 个答案:

答案 0 :(得分:0)

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

评论中提到了这个问题,但我将进一步阐述。

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

您可能想要的是使用save!,因为它会引发ActiveRecord::RecordInvalid错误并停止执行,而不是触发您之前提到的错误。 (在方法中抛出binding.pry并记下@account在尝试呼叫.id时的内容。

当您更改为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

希望这会帮助你!如果您对rspec有任何疑问/需要更多帮助,请告知我们