Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec sends emails (not storing in ActionMailer::Base.deliveries) - dont know why?

Im using rspec and when i run rake spec, the user mailer sends email through smtp and not stores the email in the ActionMailer::Base.deliveries-array (invoked by an user-observer)...

Could you give me a hint why?

# Rails version
rails -v
=> Rails 3.0.1

# Ruby version with rvm (rvm version 1.0.16)
ruby -v
=> ruby 1.9.2p7 (2010-09-29 revision 29373) [x86_64-darwin10.4.0]

# Gemfile
gem "rspec-rails", ">= 2.0.1"

Config-files:

# config/environments/test.rb
MyApp::Application.configure do
  config.action_mailer.delivery_method = :test
  config.action_mailer.raise_delivery_errors = true
end

# spec/spec_helper.rb
...
ENV["RAILS_ENV"] ||= 'test'
...

# app/models/user_observer.rb
class UserObserver < ActiveRecord::Observer
  observe User

  def after_create(record)
    puts Rails.env
    # => "test"
    UserMailer.new_user_notification(record).deliver
    puts ActionMailer::Base.deliveries.inspect
    # => []
    # Sends it via smtp!
  end
end
like image 850
BvuRVKyUVlViVIc7 Avatar asked Oct 22 '10 10:10

BvuRVKyUVlViVIc7


2 Answers

I'm so dumb... had "ActionMailer::Base.delivery_method = :smtp" in my setup_mail.rb-initializer... AAARGH....

like image 126
BvuRVKyUVlViVIc7 Avatar answered Sep 28 '22 06:09

BvuRVKyUVlViVIc7


To elaborate on the solution to this problem a little bit more:

In your config/enviroments/test.rb, by default you should have the line config.action_mailer.delivery_method = :test

What this does is tell ActionMailer not to send the email normally, but rather store the sent email in the array ActionMailer::Base.deliveries. This is helpful for testing because you can tell how many emails have been snt by using the inspect, count, length method on the ActionMailer::Base.deliveries array.

However, if you set the delivery method to something like config.action_mailer.delivery_method = :smtp, that could be overwriting your previous delivery_method = :test; therefore, your ActionMailer::Base.deliveries won't be populated.

I had done exactly this while using MailCatcher to view my emails being sent, thus causing my tests to fail, even though I was certain that emails were properly being sent!

So, make sure you're not setting a delivery_method other than :test in your test environment.

As a side note: If you're using Devise, you may want to check the Devise.mailer.deliveries array instead.

like image 21
Conner Smith Avatar answered Sep 28 '22 04:09

Conner Smith