The ActionMailer method method causes nil to return in the module when testing rspec

I have an ActionMailer class

 class UserMailer < ActionMailer::Base default from: "no-reply@spicy-millennium.com" 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) during development, it returns a Mail::Message object to me, as expected.

The place in my application where this method is called is in the module that 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 during the development process, UserMailer.submission_remind (user) returns an email message and is called, everything works as it should.

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

If I call UserMailer.submission_reminder(user) directly from the rspec test, it returns the mail program message as expected.

Here are just the lines related to ActionMailer in my /environment/test.rb configuration:

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

Any ideas why the method returns nil?

+8
ruby-on-rails ruby-on-rails-3 rspec actionmailer
source share
1 answer

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

I used the should_receive RSpec expectations, which I did not understand, actually created the layout of the class on which it is placed. So I completely mocked the UserMailer class, which meant that it never reached the actual UserMailer class.

I could not get it to work using the mock functions, so instead I changed my test to look in the UserMailer.deliveries repository, and check that the right amount of messages were posted there and that they were sent to the correct email addresses.

+16
source share

All Articles