Ruby-on-rails – Sending emails in test mode with ActionMailer in rails 3

actionmailerruby-on-railsruby-on-rails-3

I am having a slightly odd problem with sending mail in test mode with Rails 3

It seems that my mailers are not returning anything. For example I have a mailer called UserMailer. Users can make changes that require approval in the app so this has a method called changes_approved that should send the user an email notifying them that their changes have been approved.class

UserMailer < ActionMailer::Base

  default :from => "from@example.com"

  def changes_approved(user, page)

    @user = user
    @page = page

    mail(:to => user.email, :subject => "Your changes have been approved")

  end

end

In my controller I have the following line

UserMailer.changes_approved(@page_revision.created_by, @page_revision.page).deliver

However my tests fail at this point with the error:

undefined method `deliver' for nil:NilClass

When I trigger the same actions on the development site tho (http://localhost:3000 through a browser), the emails are sent out correctly and everything works quite happily

And to add further confusion, I am using devise for authentication and the emails for that seem to be working correctly both in test and development modes. Certainly I am not getting this same error and according to my email-spec tests, everythings working

So this leads me to believe that I have a problem with my mailers rather than my test mail config per se but I have no idea what. Any suggestions would be much appreciated

Thanks

Best Answer

I used https://gist.github.com/1031144 to convert

# Rails 2 method:
UserMailer.should_receive(:deliver_signup)

to

# Cumbersome Rails 3 method:
mailer = mock
mailer.should_receive(:deliver)
UserMailer.should_receive(:signup).and_return(mailer)