Daniel Huckstep Daniel Huckstep - 8 months ago 56
Ruby Question

Reuse Cucumber steps

I want to reuse some Cucumber steps but can't seem to find the right way.

I want to write a step like:

Given /^I login with (.*) credentials$/ |type|
# do stuff with type being one of "invalid" or "valid"

But then have another step like:

Given /^I login successfully$
# call "Given I login with valid credentials"

So in testing user authentication I can use the former, but most other places, I can use the latter, and not actually have to repro code.

Is there a way to call that other step, or do I just put the logic in a helper method, and call said method from each task (basically a method extraction refactoring, which, after reading my question makes me believe that's actually the best way anyway)?


UPDATE: The method described below has been deprecated. The recommended way to call a step from within another step now looks like this:

Given /^I login successfully$/
    step "I login with valid credentials" 

Old, deprecated method (for reference):

You can call steps from other steps like this:

Given /^I login successfully$/
  Given "I login with valid credentials"
  Then "I should be logged in"

If all of the scenarios within a feature require this (or other steps), you can also add a Background to each features, with the common steps, like so:

  Given I log in with valid credentials

Scenario: Change my password
  Given I am on the account page