Reuse Cucumber step definitions inside step definitions

by Melvin Ram

via: Joseph Wilk » Cucumber waves goodbye to GivenScenario.

Did you know you can reuse steps definitions inside step definitions? Here’s what I mean.

Let’s say you’re writing a scenario for Logout and it looks something like this:

Scenario: Logout
  Given I am logged in
  When I follow "Logout"
  Then I should see "Logout successful!"
  And I should get a success response

Let’s assumed that before this scenario, you wrote a scenario for logging in like this:

Scenario: Login with email
  Given I am not logged in
  And user "melvin@volcanicmarketing.com" with password "secret" and openid " " exists
  When I go to the login page
  And I fill in "email" with "melvin@volcanicmarketing.com"
  And I fill in "password" with "secret"
  And I press "Login"
  Then I should see "Login successful!"
  And I should get a success response

Now inside the step definitions for the “I am logged in” (from the Logout scenario), you could run through the process of logging in manually or you could reuse a lot of the step definitions you’ve already written for the “Login with email” scenario.

Here’s how you do it:

# features/step_definitions/auth_steps.rb

Given /^I am logged in$/ do
  Given 'I am not logged in'
  And 'user "melvin@volcanicmarketing.com" with password "secret" and openid " " exists'
  And 'I go to the login page'
  And 'I fill in "email" with "melvin@volcanicmarketing.com"'
  And 'I fill in "password" with "secret"'
  And 'I press "Login"'
end

As you can see, you just have to include the step inside single quotes. Pretty cool, huh?

PS: I am a cucumber beginner so don’t take anything in this post to be the right way to do things.

{ 1 trackback }

Simple Gotcha When Reusing Cucumber Step Definitions
May 20, 2009 at 10:42 pm

{ 0 comments… add one now }

Leave a Comment