views:

247

answers:

2

What are the best practices and tools to test email-sending using rspec with Rails?

For instance, how do I test that an email has been sent or what should I test to have efficient testing and acceptable coverage.

If you guys need an example, how would I go and test this:

class UserMailer < ActionMailer::Base

 def jobdesc_has_been_reviewed(user, title)
    @body[:title]  = title
    @body[:jobdesc]  = jobdesc
    @body[:url]  = "http://" + user.account.subdomain + "." + Constants::SITE_URL + "/jobdescs/#{jobdesc.id}"
 end

end
+1  A: 

What do you want to test exactly?

Do you want to test that the email is indeed really sent?

I don't recommend it as it will make your test slower and it really depends on the machine you are using to run your tests (network connection, smtp server).

What I usually do is make sure the controller action / model / rake task which send emails runs correctly (meaning without error, I stub the final send call). I also make sure the body, title and recipients for the mail are correct.

Edit:

Not directly related to testing but I just came over this article.

I like his point of view of using the model to send emails. So to explain a little more in details:

I would use the controller to set up view variables like @body, @title, @recipient.

So I would test that given correct parameters the mail template (which is a view) is correctly rendered. This is were mistakes can happen from my point of view.

I will update this post with example when I am back home later today.

Aurélien Bottazzini
I don't really know what I want to test... I'm looking for a correct coverage (let's say test if the email has been sent and that it has valid informations). Could you give me pointer about how you go and do what you described in your last paragraph? I'm fairly new to rspec so the more information you can give me the happier I'll be :) Thanks
marcgg
post updated. Will try to post code examples tonight
Aurélien Bottazzini
+3  A: 

email-spec looks like a good library

http://github.com/bmabey/email-spec

nicholaides
Thansk! have you tried it?
marcgg
No, I haven't tried it, but this library encapsulates the technique I use.
nicholaides
I've used email-spec with RSpec and Cucumber, and it looks to be exactly what you are looking for.
ry
I've tested it, it's great! Thanks
marcgg