Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 354
robodisco Avatar asked Jan 14 '10 10:01

robodisco


1 Answers

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 
like image 59
todd Avatar answered Sep 27 '22 19:09

todd