Ruby-on-rails – Rails – How to test ActionMailer sent a specific email in tests

actionmailerruby-on-railsunit testing

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.

Best Answer

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

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

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

mail = ActionMailer::Base.deliveries.last

assert_equal 'mikel@test.lindsaar.net', mail['from'].to_s

assert_equal 'you@test.lindsaar.net', mail['to'].to_s