簡體   English   中英

如何為在 Rails 5 中調用郵件程序的方法編寫 rspec 模擬

[英]How to write rspec mock for method that calls a mailer in rails 5

我正在嘗試從我的端點測試一個郵件方法,如下所示:

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

我該如何測試這種方法?

您在ConfirmationMailer中對send_email進行了存根,但沒有定義任何要返回的值:

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

您需要定義一個由存根方法返回的值(使用#and_return )或調用 original :在允許(ConfirmationMailer)之前接收(:send_email).and_call_original end

也就是說,我認為這不是測試是否發送 email 的最佳方法。 更好地使用此答案中的建議:配置config.action_mailer.delivery_method =:test並在全局數組ActionMailer::Base.deliveries上斷言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM