How to Remove Duplication in Cucumber Tests Using Scenario Outlines

Gojko Adzic has a new blog post demonstrating the new table parameter support in Cuke4Nuke. Table parameters are an important part of Cucumber. They’re great for setting up data and asserting that lists are what you expect. But I use them much less often than the other kind of table in Cucumber, scenario outlines.

Scenario outlines are the solution to repetitive Given-When-Then scenarios. Extending the WatiN example in my previous screencast, we might find ourselves writing scenarios like:


Scenario: Search - richard lawrence
Given I'm on the search page
When I search for "richard lawrence"
Then I should see "www.richardlawrence.info" in the results

Scenario: Search - pickaxe
Given I'm on the search page
When I search for "pickaxe"
Then I should see "www.ruby-doc.org/docs/ProgrammingRuby/" in the results

Scenario: Search - cuke4nuke
Given I'm on the search page
When I search for "cuke4nuke"
Then I should see "github.com/richardlawrence/Cuke4Nuke" in the results

This kind of repetition gets old fast, both to write and to read. Scenario outlines allow us to separate the structure of the test, which doesn’t change, from the data, which does. Here are the same scenarios refactored:


Scenario Outline: Search
Given I'm on the search page
When I search for ""
Then I should see "" in the results

Examples:
| query | expected_result |
| richard lawrence | www.richardlawrence.info |
| pickaxe | www.ruby-doc.org/docs/ProgrammingRuby/ |
| cuke4nuke | github.com/richardlawrence/Cuke4Nuke |

Cucumber turns each example—each table row—into a concrete scenario before looking for matching step definitions in Cuke4Nuke, so nothing needs to change on the Cuke4Nuke side.

In most cases, I recommend starting with concrete scenarios and refactoring to scenario outlines once you have a few scenarios working with the correct step definitions.

Related Articles

Responses