andhapp Random ramblings

Using cucumber-0.9.2 and cucumber-rails-0.3.2 with I18n

I have previously, blogged about using factory_girl with clearance and this post (quite similar to that one) describes the need to use messages (notice, success or failure) in your locale file with cucumber and how to go about using them. Needless to say, this pertains only to the Rails crowd but I guess anyone can set-up their gems or ruby aps to extract similar behaviour. I have been using cucumber with Rails3 and been blogging about my experiences for last couple of weeks.

Imagine, you are writing a feature and you would like to test that the correct flash message gets displayed when something goes wrong or as a notification to the user. In order to make sure, I use the same message across the board I would like to add them to my locale file and read it from there. Instead of having to copy paste them since with cucumber outward-in TDD approach one writes the feature then jumps into write controller and model specs to make the feature pass. Now, in order to achieve that all you gotta do is load the i18n library when the cucumber features are run. So, just add the following to env.rb:

require "i18n"

But, I can’t use the following snippet in my scenarios. How will I use it with cucumber?

I18n.translate :invalid, :scope => [:login, :errors, :messages]

Simple, just use it in your step definitions. Instead of the following scenario:

Scenario: Logging in
  Given I am on sign in page
  When I press "Log in"
  Then I should see error messages

use this scenario:

Scenario: Logging in
  Given I am on sign in page
  When I press "Log in"
  Then I should see error messages

In your step definitions, add a new step for “I should see login failure messages” like this:

Then /^I should see login failure messages$/ do
   Then %{I should see "#{I18n.translate :invalid, :scope => [:login, :errors, :messages]}"}
end

And that’s it. It does sound like a lot of work but it took me under 15 minutes to get it working.