如何为在Rails 5中调用邮件程序的方法编写RSpec模拟

我正在尝试从我的端点测试一个邮递员方法,如下所示:

Confirmationmailer.send_email(email).deliver_later

相应的规格如下:

let(:confirmation_mailer_stub) { instance_double Confirmationmailer }

before do
  allow(Confirmationmailer).to receive(:send_email)
end

it 'sends confirmation email' do
  call_endpoint
  expect(confirmation_mailer_stub).to change { actionmailer::Base.deliveries.count }.by(1)
end

但是我有一个错误:

  

NoMethodError:          nil:NilClass的未定义方法`deliver_later'

send_email方法非常简单:

def send_email(email)
  mail(to: email,cc: email)
end

如何测试此方法?

hfny718hf 回答:如何为在Rails 5中调用邮件程序的方法编写RSpec模拟

您在send_email中打了ConfirmationMailer,但未定义要返回的任何值:

before do
  allow(ConfirmationMailer).to receive(:send_email)
end

您需要定义存根方法(使用#and_returncall original返回的值: 做之前   允许(ConfirmationMailer)。接收(:send_email).and_call_original 结束

也就是说,我认为这不是测试是否发送电子邮件的最佳方法。更好地使用this answer的建议: 配置config.action_mailer.delivery_method = :test并在全局数组ActionMailer::Base.deliveries上声明。

本文链接:https://www.f2er.com/3153948.html

大家都在问