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

时间:2017-03-02 09:51:17

标签: ruby-on-rails rspec

我需要确保运行导入程序会导致发送电子邮件。

这是我到目前为止所得到的:

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

失败了:

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

这显然无法解决,因为我期望Mailer类接收(实例)方法调用。但是,如何才能获得将接收呼叫的邮件程序实例?你如何测试一个单位的方法触发某个邮件?

2 个答案:

答案 0 :(得分:2)

我认为delivery_confirmation方法实际上会返回一个Mail对象。问题是ActionMailer将调用邮件对象的deliver方法。您已经设置了一个期望来截断delivery_confirmation方法,但是您没有指定返回值应该是什么。试试这个

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

答案 1 :(得分:1)

如果我找对你,

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

将测试将接收呼叫的邮件程序实例。

为了获得更高的精确度,您可能希望使用OrderMailer的特定实例设置测试(假设为order_mailer)并按以下方式编写您的期望

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