Using rspec to test ActionMailer with should_receive-Collection of common programming errors

You’re likely calling Mailer.notification_to_sender.deliver in your controller, or better yet, a background job. I’m guessing notification_to_sender probably takes a parameter as well.

Anyways, when you call the notification_to_sender method on Mailer you’re getting back an instance of Mail::Message that has the deliver method on it. If you were simply doing Mailer.notification_to_sender without also calling deliver, you could run what you have there with the comments and all would be fine. I would guess you’re also calling deliver though.

In that case your failure message would be something like

NoMethodError:
  undefined method `deliver' for nil:NilClass

That is because nil is Ruby’s default return value much of the time, which Rails also inherits. Without specifying the mailer = mock and .and_return(mailer) parts, when the controller executes in context of the test then notification_to_sender will return nil and the controller will try to call deliver on that nil object.

The solution you have commented out is to mock out notification_to_sender‘s return value (normally Mail::Message) and then expect that deliver method to be called on it.