Main Content

Scenario outlines - tables of values to test - in Gherkin / Cucumber

Archive - Originally posted on "The Horse's Mouth" - 2015-10-23 13:37:27 - Graham Ellis

Rather that writing large numbers of scenarios in Gherkin, we can write Scenario Outlines and then supply Example rows of data to fill in to those outlines - a great way of specifying a series of similar behaviours - a list of "if I do aaa with the value x then I get the result y" statements where x and y will vary, but aaa will be the same thing many times over.

This follows on from the example described [here].

Here's an example of a feature file using a scenario outline:

 Feature: Checking we know station names and passenger counts
 
 Scenario Outline: 
 When we ask for the full name for "<tlc>"
 Then we are told it is "<fullname>"
 Then we are also told it had <journeys> passengers
 
 Examples:
   | tlc  |  fullname      |  journeys   |
   | SWI  |  Swindon       |  3350444    |
   | DMH  |  Dilton Marsh  |  20084      |
   | PLY  |  Plymouth      |  2445464    |
   | SPP  |  Shippea Hill  |  12         |


Here is the implementation of those features:

  When(/^we ask for the full name for "(.*?)"$/) do |arg1|
    @station = loadStationFactory[arg1]
  end
  
  Then(/^we are told it is "(.*?)"$/) do |arg1|
    expect(@station.getFullName).to eq(arg1)
  end
  
  Then(/^we are also told it had (\d+) passengers$/) do |arg1|
    expect(@station.getPassengers).to eq(arg1.to_i)
  end


And here are the results when we run all of those tabulated tests:

 munchkin:lr grahamellis$ cucumber -s cucTables
 Feature: Checking we know station names and passenger counts
 
   Scenario Outline: 
     When we ask for the full name for "<tlc>"
     Then we are told it is "<fullname>"
     Then we are also told it had <journeys> passengers
 
     Examples: 
       | tlc | fullname     | journeys |
       | SWI | Swindon      | 3350444  |
       | DMH | Dilton Marsh | 20084    |
       | PLY | Plymouth     | 2445464  |
       | SPP | Shippea Hill | 12       |
 
 4 scenarios (4 passed)
 12 steps (12 passed)
 0m0.259s
 munchkin:lr grahamellis$


Source:
Station feature file - [here]
Step implemenation - [here]
and the file we're testing - from another module
stations.py - [here]