存根上的 RSpec 期望失败



这是我想测试期望的电话:

UserMailer.invoice_paid(user, invoice).deliver_later

Rails 5 ActionMailer 在:test模式下的行为似乎在 ApplicationMailer 类的每个方法上都返回 nil。这应该没问题,因为我可以像这样存根:

invoice_paid_dbl = double(ActionMailer::MessageDelivery)
allow(UserMailer).to receive(:invoice_paid).and_return(invoice_paid_dbl)

此预期失败:

expect(UserMailer).to receive(:invoice_paid).once

虽然这个通过:

expect(invoice_paid_dbl).to receive(:deliver_later).once

这难道不应该是不可能的吗?我想也许方法链混淆了 RSpec,但将行拆分为这个没有效果:

mail = UserMailer.invoice_paid(user, invoice)
mail.deliver_later

.with(any_args)添加到存根和期望也没有影响(因为无论如何这是默认值(。预期失败:任何参数为 1 次,收到:任何参数为 0 次。

不明白你是如何存根方法的,但认为以下内容对你有用

您正在尝试存根方法链,因此需要使用stub_chain而不是stub

UserMailer.stub_chain(:invoice_paid, :deliver_later).and_return(:invoice_paid_dbl)

我希望这将起作用并解决您的问题。有关更多详细信息,请查看 docs

我会把这个问题留下来,以防它对其他人有帮助,但这实际上是一个愚蠢错误的结果。我之前在it街区expect(UserMailer).to receive(:invoice_paid),它正在通过。这是这种类型的第二个期望失败了。哎呀。

最新更新