[rspec-users] Spec'ing ActionMailer

Craig Demyanovich cdemyanovich at gmail.com
Sun Feb 4 14:56:51 EST 2007

On Feb 4, 2007, at 1:53 PM, s.ross wrote:

> Good morning (Pacific Time). I have a controller action that, as a
> side-effect, sends an email to an administrator. I want it to do
> something like this:
> specify "when someone successfully signs up, an email should be sent
> to the administrator with the person's contact page" do
>    post :signup, {...lots o' params}
>    response should_be success
>    # here's where I want to see whether email was sent. Of course,
> the code is bogus.
>    email.body.should have_tag(:p, :content => /page=/)
> end
> Is there some way to reach in and grab the message (what I've written
> as "email" above) so I can test the various parameters such as the
> "to" array and the email contents? I'm most interested in whether the
> controller/mailer interaction is working properly. Also, can I use
> the DOM select expectations or is it a simple matcher?

On my first Rails project, I had to test whether a controller sent  
email when a job application was submitted. Fortunately, ActionMailer  
doesn't deliver email when running in a test environment. Rather, it  
records deliveries and makes them available via  
ActionMailer::Base.deliveries. I demonstrate this below. Note that  
the chapter on ActionMailer in AWDwR was very helpful to me, since it  
described a couple of ways to test sending email. Anyway, here's the  
code. Perhaps you can translate it into some specs.


require File.dirname(__FILE__) + '/../test_helper'
require 'jobs_controller'

# Re-raise errors caught by the controller.
class JobsController; def rescue_action(e) raise e end; end

class JobsControllerTest < Test::Unit::TestCase
   fixtures #...

   def setup
     @emails     = ActionMailer::Base.deliveries

   def test_submit_application
     post :submit_application, :job_application => {
       # lots of params

     assert_response :success
     assert_template 'submit_application'

     assert_equal(2, @emails.size)

     email = @emails.first
     assert_match(/Confirm/, email.subject)
     assert_equal('john at doe.com', email.to()[0])

     email = @emails[1]
     assert_match(/Resume received/, email.subject)
     assert_equal('jobs at host.com', email.to()[0])

More information about the rspec-users mailing list