Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionMailer method call returning nil in module while rspec testing

I have an ActionMailer class

class UserMailer < ActionMailer::Base 
  default from: "[email protected]" 

  def submission_reminder user 
    @user = user           
    mail :to => user.email, :subject => "Your timesheet needs to be submitted!" 
  end    
end

If I call UserMailer.submission_reminder(current_user) in development it returns me a Mail::Message object like expected.

The place in my application where this method is called is in a module I have in the lib folder:

module TimesheetSubmissionNotifier                            
  def self.send_submission_reminders
    User.all.each { |user| UserMailer.submission_reminder(user).deliver }
  end
end

When I call TimesheetSubmissionNotifier.send_submission_reminders in development, UserMailer.submission_remind(user) returns the mail message and deliver is called, everything works as it should.

The problem is when I call TimesheetSubmissionNotifier.send_submission_reminders through an rspec test, UserMailer.submission_reminder(user) returns nil.

If I call UserMailer.submission_reminder(user) directly from an rspec test, it returns the mailer message like expected.

Here are the only lines related to ActionMailer in my config/environment/test.rb:

config.action_mailer.delivery_method = :test 
config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Any ideas why the method is returning nil?

like image 793
dnatoli Avatar asked Mar 27 '12 05:03

dnatoli


1 Answers

For those who have a similar problem, I found the issue.

I was using the should_receive RSpec expectation, which I didn't realise actually created a mock of the class it is placed on. So I was mocking out the UserMailer class entirely which meant that it was never reaching the actual UserMailer class.

I couldn't get it working by using the mock functions, so instead I changed my test to look at the UserMailer.deliveries store and check that the right amount of messages are put in there and that they are being sent to the right email addresses.

like image 174
dnatoli Avatar answered Nov 15 '22 19:11

dnatoli