这是我正在try 测试的代码:

Appsignal.send_error(error) do |transaction|
  transaction.set_tags({
    customer_communication_id: customer_communication_id,
    interaction_reason_id: interaction_reason_id,
  })
end

我想测试三件事:

  1. 错误正在被传递.
  2. 该set_tag在块中被调用.
  3. 在设置标记调用中设置了正确的标记.

对于测试1:

expect(Appsignal).to receive(:send_error).with(an_instance_of(ActiveRecord::RecordNotFound))

这起到了预期的作用.

我try 了几种方法,但不知道如何测试2和3. 在#3上,我想用如下内容来测试标记是否正确:

hash_including(customer_communication_id: customer_communication.id, interaction_reason_id: InteractionReason::PAYMENT_REMINDER_TEXT.id)

推荐答案

关于2:使用TestDouble,类似于(伪代码)

transaction = instance_double(<whatever class it is expected to be>)
allow(Appsignal).to receive(:send_error).and_yield(transaction)
allow(transaction).to receive(:set_tags)

<do something>

expect(Appsignal)
  .to have_received(:send_error)
  .with(<expected error>)

expect(transaction)
  .to have_received(:set_tags)
  .with(
    customer_communication_id: customer_communication_id, 
    interaction_reason_id: interaction_reason_id
  )

关于3:解耦,set_tags应该单独测试,而不是1和2.如果它是您的代码,只需用良好的单元测试来覆盖它(如果它是由第三方库提供的,则忽略它-它应该由第三方测试进行测试;嗯,希望是:)

Ruby-on-rails相关问答推荐

在Rails中,如何将帮助器方法添加到属性/列?

获取所有属于模型的嵌套对象

Rails/Rspec中的测试文章创建

如何保持 en.yml DRY?

Ruby on rails 查询不知道怎么写

设计 token_authenticable 已弃用,有什么替代方案?

rails4 未知编码名称 - CP720

使用devise gem点击确认链接后避免登录?

如何在 RoR 中实现成就系统

具有 has_many 关联的 FactoryGirl build_stubbed 策略

不允许请求来源:使用 Rails5 和 ActionCable 时的 http://localhost:3001

对象不支持此属性或方法 Rails Windows 64bit

我收到在扫描下一个令牌时发现无法启动任何令牌的字符

将图标添加到 Rails 应用程序

从 Rails 中的控制器调用辅助方法时出现未定义的方法

ActiveRecord 事务中的错误处理?

如何在两个字段上对 ruby​​/rails 进行排序?

如何强制 RSpec 测试失败?

ActiveRecord 何时会保存关联?

Rails:如何在rails中使用dependent::destroy?