Writing a spec for sending a mail via API
I want an E-Mail to be sent using a background process whenever an Invite was generated.
What I currently have is this approach: The Invite model has the method send_mail, which sends an E-Mail using the Mandrill API and gem. It also has the method queue_mail adds InviteMailer with the invite's ID to the queue using Resque.
However… Since I'm having sort of a really hard time writing specs for this, I assume this might not be the best approach to send mails.
What I mainly want and need to test:
- was the mail added to the queue?
- is InviteMailer working properly?
- does the mail contain the correct vital information?
Vital informations are: sent to the correct person, contains a link to a specific site and some specific data/text; also I'm not sure how to get the current host to the link.
I don't think this is a rare thing to do, so I wonder what the best practices are.
My testing environment: rspec, capybara, factory girl. I already added VCR, to cache the API-request.
You can use Mailcatcher to fake your mail server, and check received mail via web API:
- Catches all mail and stores it for display.
- Shows HTML, Plain Text and Source version of messages, as applicable.
- Rewrites HTML enabling display of embedded, inline images/etc and open links in a new window. (currently very basic)
- Can send HTML for analysis by Fractal.
- Lists attachments and allows separate downloading of parts.
- Download original email to view in your native mail client(s).
- Command line options to override the default SMTP/HTTP IP and port settings.
- Mail appears instantly if your browser supports WebSockets, otherwise updates every thirty seconds.
- Growl notifications when you receive a new message.
- Runs as a daemon run in the background.
- Sendmail-analogue command, catchmail, makes using mailcatcher from PHP a lot easier.
- Written super-simply in EventMachine, easy to dig in and change.
- gem install mailcatcher
- Go to http://localhost:1080/
- Send mail through smtp://localhost:1025
A fairly RESTful URL schema means you can download a list of messages in JSON from /messages, each message's metadata with /messages/:id.json, and then the pertinent parts with /messages/:id.html and /messages/:id.plain for the default HTML and plain text version, /messages/:id/:cid for individual attachments by CID, or the whole message with /messages/:id.source.