DRY up your Cucumber Steps

Update (13th Jume 2012): This is an old, old post that still gets a lot of hits. I don’t recommend this practice anymore. Instead, I recommend composing Ruby methods that carry out these actions. For more details, please see The Cucumber Book.

A while back, I asked the Cucumber team for the ability to call in the steps of one scenario from another.

The canonical example of this is the ‘log in’ scenario:

Scenario: User logs in
  Given there is a User whose username is "matt"
  And I follow "log in"
  And I enter "matt" in "username"
  And I enter the User's password in "password"
  And I press "Log In"
  Then I should be logged in
  And I should see the text "Hello matt"

Phew. Now obviously I don’t want all this noise in the scenario every time I specify behaviour that requires a logged in user. I want to write something like this:

Scenario: User views their dashboard
  Given I am logged in
  And I follow the "dashboard" link
  Then I should see "This is your dashboard"

Thanks to the fabulous creativity of the Cucumber community, this is now possible. It’s also highly recommended, as it’s a great way to help you keep your step files tidy and DRY of excess duplication.

Given /I am logged in/ do
  steps %{
    Given there is a User
    When I follow "log in"
    And I enter "#{User.first.username}" in "username"
    And I enter "#{User.first.password}" in "password"
    And I press "Log In"
  }
end

I’m doing this more and more now – writing simple ‘building block’ steps and assembling them to make steps that read nicely and make sense to the stakeholders.