简体   繁体   中英

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

I'm trying to test a mailer method from my endpoint which looks like this:

ConfirmationMailer.send_email(email).deliver_later

And the corresponding spec looks like this:

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

But I've got an error:

NoMethodError: undefined method `deliver_later' for nil:NilClass

The send_email method is quite simple:

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

How can I test this method?

You stubbed send_email in ConfirmationMailer without defining any value to be returned:

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

You need to define a value returned by the stubbed method (with #and_return ) or call original : before do allow(ConfirmationMailer).to receive(:send_email).and_call_original end

That said, I think it's not the best way to test if email is sent. Better use the advice from this answer : configure config.action_mailer.delivery_method =:test and assert on global array ActionMailer::Base.deliveries .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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