Rails - How do you test ActionMailer sent a specific email in tests

robodisco picture robodisco · Jan 14, 2010 · Viewed 37.8k times · Source

Currently in my tests I do something like this to test if an email is queued to be sent

assert_difference('ActionMailer::Base.deliveries.size', 1) do       
  get :create_from_spreedly, {:user_id => @logged_in_user.id}
end

but if i a controller action can send two different emails i.e. one to the user if sign up goes fine or a notification to admin if something went wrong - how can i test which one actually got sent. The code above would pass regardless.

Answer

todd picture todd · Aug 19, 2010

As of rails 3 ActionMailer::Base.deliveries is an array of Mail::Message's. From the mail documentation:

#  mail['from'] = '[email protected]'
#  mail[:to]    = '[email protected]'
#  mail.subject 'This is a test email'
#  mail.body    = 'This is a body'
# 
#  mail.to_s #=> "From: [email protected]\r\nTo: you@...

From that it should be easy to test your mail's in an integration

mail = ActionMailer::Base.deliveries.last

assert_equal '[email protected]', mail['from'].to_s

assert_equal '[email protected]', mail['to'].to_s