Sending email in test mode using ActionMailer on rails 3

I have a slightly strange problem sending mail in test mode with Rails 3

My mail seems to be returning nothing. For example, I have a UserMailer mailer. Users can make changes that require approval in the application, so he has a method called changes_approved, which should send a message to the user with a notification 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 with this error:

undefined `deliver 'method for nil: NilClass

tho (http://localhost: 3000 ), ,

, , , , , . , ​​ , ,

, , , , , .

+3
4

, ,

, , . ,

UserMailer.should_receive(:changes_approved).with(user, page)

, , , , . , . ActionMailer:: Base.deliveries.last, , , , .

, ,

+1

https://gist.github.com/1031144

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

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

: , UserMailer.changes_approved mock, nil ( shoulda , ).

My code looked like this (modified to use your example):

UserMailer.expects(:changes_approved).once

I installed it using an additional stub:

@mailer = stub(:deliver)
UserMailer.expects(:changes_approved).once.returns(@mailer)

Now nil is replaced with @mailer.

+5
source

To check the mail program with a delayed action, we first need to change the delayed_job configuration (in config / initializers / delayed_job_config.rb) to

Delayed::Worker.delay_jobs = !Rails.env.test?

and in your tests the expectation should be set to

mock_mail = mock(:mail)
mock_mail.should_receive(:deliver)
UserMailer.should_receive(:changes_approved).with(user, page).and_return(mock_mail)
+2
source

Source: https://habr.com/ru/post/1778979/


All Articles