|The Secret Ninja Cucumber Scrolls|
The feature file we used in the Chapter 5, Cucumber feature files has 13 lines for two scenarios. To specify a business rule properly we would most likely have to add many more scenarios, that illustrate what happens when a ninja is not experienced enough to engage a samurai, when it becomes experienced enough to engage Chuck Norris, not to mention other ninjas and types of opponents. If we had to add four lines for every new scenario, the file would quickly become too big to be readable.
To address this, Gherkin supports scenario outlines. Scenario outlines are essentially template scenarios, allowing us to provide the scenario structure once and then illustrate the behaviour with different combinations of parameters. Scenario outlines are a great way to consolidate and simplify related scenarios and present them in a way that is easier to understand. Here is an example:
Scenario Outline: third-level ninjas engage samurai Given the ninja has a <belt level> level black-belt When attacked by <opponent> Then the ninja should <expected action> Examples: |belt level |opponent |expected action | |third |a samurai |engage the opponent | |third |Chuck Norris |run for his life |
The interesting parts are in bold:
This feature file is functionally equivalent to the one we used in the previous chapter. The same step definitions will be used to execute it. In fact, try that yourself. Delete the two step definitions we used earlier, or create a new feature file and run it using Cucumber. You'll see the same results, just formatted differently.
What's nice about this format is that we can easily add more examples. To make the specification stronger, let's
add another example that shows that second level ninjas don't even fight against samurai. We add just one line to the table:
Run Cucumber again and the test should fail. If you are running Ruby, you should get an error similar to the one in Figure 7.1, “Ruby ninjas engage samurai even when they should not”. If you are running Java, you should get an error similar to the one in Figure 7.2, “Java ninjas engage samurai even when they should not”.
For a homework assignment, change the Ninja class to make this test pass and re-run Cucumber to confirm that you have fixed it.
Scenario outlines are one of the most important tools for Cucumber ninjas, as they allow us to describe complex scenario groups easily and make the files shorter and easier to understand.