Daniel Cukier
Daniel Cukier

Reputation: 11952

Rails controller does not deliver email in test with ActiveMailer

We have a Rails controller that send email:

class UsersController
  def invite
    mail = WeeklyReport.weekly_report(current_user).deliver
    flash[:notice] = "Mail sent!"
    redirect_to controller: "partners", action: "index"
  end
end

class WeeklyReport < ActionMailer::Base
  def weekly_report(recipient)
    @data = recipient.data
    mail(:to => "#{recipient.name} <#{recipient.email}>", :subject => "Weekly report")
  end
end

When testing the controller manually, it is actually sending the email. But the controler test is failing:

it "should send mail" do
  get :invite

  response.should redirect_to "/partners/index"
  request.flash[:notice].should eql("Mail sent!")

  deliveries.size.should == 1 ### TEST FAILS HERE!

  last_email.subject.should ==  "Weekly report"
  last_email.to[0].should == '[email protected]'
end

# Failure/Error: deliveries.size.should == 1
#   expected: 1
#        got: 0 (using ==)

my test env is correctly configured: config.action_mailer.delivery_method = :test

And the WeeklyReport test is working fine:

  it "should send weekly report correctly" do
    @user = FactoryGirl.create_list(:user)
    email = WeeklyReport.weekly_report(@user).deliver
    deliveries.size.should == 1
  end

Why the controller test is failing?

Edit 1: I noticed that emails are actually being delivered (real emails), ignoring the config: config.action_mailer.delivery_method = :test - what could it be?

Edit 2: My test.rb file:

  config.cache_classes = true
  config.eager_load = false
  config.serve_static_assets  = true
  config.static_cache_control = "public, max-age=3600"
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_mailer.default_url_options = { :host => 'dev.mydomain.com' }
  config.action_dispatch.show_exceptions = false
  config.action_controller.allow_forgery_protection = false
  config.active_record.default_timezone = :local
  config.action_mailer.delivery_method = :test
  config.active_support.deprecation = :stderr

Upvotes: 1

Views: 594

Answers (1)

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8132

Like you said, it is not using your test setting, then there must be the problem with something with environment. Try explicitly setting it before it loads the specs and test it.

it "should send mail" do
  ::ActionMailer::Base.delivery_method = :test
  get :invite

  response.should redirect_to "/partners/index"
  request.flash[:notice].should eql("Mail sent!")

  ::ActionMailer::Base.deliveries.size.should == 1     
  last_email.subject.should ==  "Weekly report"
  last_email.to[0].should == '[email protected]'
end

Upvotes: 3

Related Questions