If you haven’t yet discovered Cucumber, check out these Railscasts:
- beginning with Cucumber
- more on Cucumber
If you’re already up to speed with the basics of Cucumber, here is a really useful way to test emails using Cucumber.
First we need to install the email-spec plugin by Ben Mabey:
script/plugin install git://github.com/bmabey/email-spec.git
Next, we need to add the following line to features/support/env.rb just after the line “require ‘cucumber/rails/world’”:
require 'email_spec/cucumber'
This loads the neccessary helper methods that the email steps rely on.
Next, type the following in your terminal:
script/generate email_spec
This command will add a new file in features/step_definitions/ called email_steps.rb with loads of handy steps you can include in your scenarios:
Given no emails have been sent
When I open the email
When I follow "[link]" in the email
When "[address]" opens the email with subject "[some text]"
When "[address]" opens the email with text "[some text]"
When I click the first link in the email
Then I should receive an email
Then "[address]" should receive n emails
Then "[address]" should have n emails
Then "[address]" should not receive an email
Then I should see "[some text]" in the subject
Then I should see "[some text]" in the email
If you have a look in email_steps.rb you should also see a small module called EmailHelpers with a method current_email_address. This method specifies the email address to be used when you write a step from a first person perspective (e.g. Then I should have 2 emails). What you put in this method really depends on how your application works but generally you’ll be sending emails to the user who is currently logged in or your own admin email address so I usually set this to:
module EmailHelpers
def current_email_address
if assigns(:current_user)
assigns(:current_user).email
else
"admin@mydomain.com"
end
end
end
which can be simplified to:
module EmailHelpers
def current_email_address
assigns(:current_user) ? assigns(:current_user).email : "admin@mydomain.com"
end
end
Here is an example of a simple scenario using email-spec. The scenario tests that, after creating an account, the new user receives an email with a link they should follow to activate their account:
Scenario: new user successfully activates their account
Given I have no users
When I sign up with email "my@email.com"
Then "my@email.com" should receive 1 email
When "my@email.com" opens the email with text "activate your account"
And I follow "activate your account" in the email
Then I should be on the account active page
And I should see "Your account is now active"
And I should be logged in
You can also write your own custom email steps combining a few of the helper methods provided by email-spec to make your scenarios even simpler.
Mailer integration testing made easy!
Testing Your Mailers Using Cucumber and Email-Spec
No comments:
Post a Comment