如何使用rspec测试ActionMailerliver_later [英] How to test ActionMailer deliver_later with rspec
问题描述
尝试使用delay_job_active_record升级到Rails 4.2.我没有为测试环境设置delay_job后端,以为作业将立即执行.
trying to upgrade to Rails 4.2, using delayed_job_active_record. I've not set the delayed_job backend for test environment as thought that way jobs would execute straight away.
我正在尝试使用Rspec测试新的'deliver_later'方法,但不确定如何.
I'm trying to test the new 'deliver_later' method with Rspec, but I'm not sure how.
旧控制器代码:
ServiceMailer.delay.new_user(@user)
新控制器代码:
ServiceMailer.new_user(@user).deliver_later
我曾经这样测试过它:
expect(ServiceMailer).to receive(:new_user).with(@user).and_return(double("mailer", :deliver => true))
现在我在使用它时出错.(双邮件程序"收到意外消息:带有(无参数)的deliver_later)
Now I get errors using that. (Double "mailer" received unexpected message :deliver_later with (no args))
只是
expect(ServiceMailer).to receive(:new_user)
对于nil:NilClass,也使用未定义的方法'deliver_later'"失败了
fails too with 'undefined method `deliver_later' for nil:NilClass'
我尝试了一些示例,这些示例可让您查看是否使用ActiveJob中的test_helper将作业排入了队列,但我没有设法测试排队的正确作业.
I've tried some examples that allow you to see if jobs are enqueued using test_helper in ActiveJob but I haven't managed to test that the correct job is queued.
expect(enqueued_jobs.size).to eq(1)
如果包括test_helper,则通过,但是不允许我检查它是否发送了正确的电子邮件.
This passes if the test_helper is included, but it doesn't allow me to check it is the correct email that is being sent.
我想做的是:
- 测试正确的电子邮件已排队(或在测试环境中立即执行)
- 具有正确的参数(@user)
有什么想法吗?谢谢
推荐答案
如果我对您的理解正确,则可以执行以下操作:
If I understand you correctly, you could do:
message_delivery = instance_double(ActionMailer::MessageDelivery)
expect(ServiceMailer).to receive(:new_user).with(@user).and_return(message_delivery)
allow(message_delivery).to receive(:deliver_later)
关键是您需要以某种方式为 deliver_later
提供一个双重标记.
The key thing is that you need to somehow provide a double for deliver_later
.
这篇关于如何使用rspec测试ActionMailerliver_later的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!