简体   繁体   English

Rails,RSpec:如何测试,特定的邮件程序操作被触发

[英]Rails, RSpec: How to test, that a specific mailer action gets triggered

I need to ensure that running an importer results in sending out an email. 我需要确保运行导入程序会导致发送电子邮件。

This is what I got so far: 这是我到目前为止所得到的:

describe '#import' do
  it 'triggers the correct mailer and action', :vcr do
    expect(OrderMailer).to receive(:delivery_confirmation).with(order)

    Importer.new(@file).import
    remove_backed_up_file
  end
end

It fails with: 它失败了:

pry(#<ActiveRecord::ConnectionAdapters::TransactionManager>)> error
=> #<NoMethodError: undefined method `deliver_now' for nil:NilClass>

Which obviously can't work out as I am expecting the Mailer class to receive the (instance) method call. 这显然无法解决,因为我期望Mailer类接收(实例)方法调用。 But how can I get a hold of the mailer instance that will receive the call? 但是,如何才能获得将接收呼叫的邮件程序实例? How would you test that a unit's method triggers a certain mailer? 你如何测试一个单位的方法触发某个邮件?

I assume the delivery_confirmation method in reality returns a Mail object. 我假设delivery_confirmation方法实际上返回一个Mail对象。 The problem is that ActionMailer will call the deliver method of the mail object. 问题是ActionMailer将调用邮件对象的deliver方法。 You've set an expectation stubbing out the delivery_confirmation method but you haven't specified what should be the return value. 您已设置了对delivery_confirmation方法的预期,但您尚未指定返回值。 Try this 尝试这个

mail_mock = double(deliver: true)
# or mail_mock = double(deliver_now: true)
expect(mail_mock).to receive(:deliver)
# or expect(mail_mock).to receive(:deliver_now)
allow(OrderMailer).to receive(:delivery_confirmation).with(order).and_return(mail_mock)
# the rest of your test code

If I got you right, 如果我找对你,

expect_any_instance_of(OrderMailer).to receive(:delivery_confirmation).with(order)

will test the mailer instance that will receive the call. 将测试将接收呼叫的邮件程序实例。

For more precision you may want to set up your test with the particular instance of OrderMailer (let's say order_mailer ) and write your expectation the following way 为了更加精确,您可能希望使用OrderMailer的特定实例(比如order_mailer )设置测试, OrderMailer以下方式编写您的期望

expect(order_mailer).to receive(:delivery_confirmation).with(order)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM