Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: Testing to make sure email is not sent

I am running a test to make sure emails are not sent to certain users:

it "does not send reminders to users who are not subscribed" do
        expect(ReminderMailer).not_to receive(:send_reminder).with("whatever", user.id).and_return(double(deliver_now: true))
        book.send_reminders("whatever", user.id)
      end

Book.rb

def send_reminders(medium, user_id)
    ReminderMailer.send_reminder(medium, user_id).deliver_now
end

But the current test is saying:

and_return is not supported with negative message expectations

If I remove the and_return portion:

it "does not send reminders to users who are not subscribed" do
        expect(ReminderMailer).not_to receive(:send_reminder).with("whatever", user.id)
        book.send_reminders("whatever")
      end

Then the test fails because:

undefined method `deliver_now' for nil:NilClass

How can I test that an action mailer method with specific parameters are not called?

like image 328
Jackson Cunningham Avatar asked Mar 13 '23 19:03

Jackson Cunningham


1 Answers

There are some problems with your code:

  1. The number of arguments passed to method send_reminders seems wrong (you pass only 1 argument 'whatever' but no user id)

  2. I don't see any condition to filter user, is it in ReminderMailer's method send_reminder? So it will call send_reminder anyway, just won't send mail, right? It's not what you expected.

If so, you could try this:

expect {
  book.send_reminders("whatever")
}.not_to change(ActionMailer::Base.deliveries, :count)

It will expect no mail was actually sent. Good luck bro!

like image 196
Hoang Phan Avatar answered Mar 23 '23 17:03

Hoang Phan