1

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?

mrzasa
  • 22,895
  • 11
  • 56
  • 94
mr_muscle
  • 2,536
  • 18
  • 61
  • Sounds like you may have misunderstood how test doubles and mocking work. If you're providing a double for an object, you can't expect it to do any of its original functions. Can you show the code you're testing in full, and the test you've written in full? – Jon Nov 06 '19 at 08:36

1 Answers1

0

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.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • After adding `and_call_original` I've got different error -> ```expected `ActionMailer::Base.deliveries.count` to have changed by 1, but was not given a block``` – mr_muscle Nov 06 '19 at 09:03
  • _Either_ use stubbing _or_ check deliveries count. Don't do both. – mrzasa Nov 06 '19 at 09:17
  • So how my test should looks like? is it ```expect{ ActionMailer::Base.deliveries.count }.to change.by(1)``` without stubbing? – mr_muscle Nov 06 '19 at 09:26
  • Configure AJ correctly :https://stackoverflow.com/a/39712145/580346 – mrzasa Nov 06 '19 at 09:34