Main Content

Testing your new class - first steps with cucumber

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

A recent article ([here]) showed you how we build up a series of classes, each with their own piece of test code, into applications.

It's all very well putting a piece of test code in the bottom of our class definition file - and that's a useful thing to do - but it's just a single test, and it doesn't provide for a management system for tests, nor for regression testing where new tests are added to a suite as more code gets added to the class. That's where cucumber comes in - and we have a whole separate module on that - see [here].

Using cucumber, we describe a behaviour in a feature file (using the gherkin language):

  Feature: Checking we know station names
  
  Scenario:
  When we ask for the full name for "MKM"
  Then we are told it is "Melksham"
  
  Scenario:
  When we ask for the full name for "PLY"
  Then we are told it is "Plymouth"
  
  Scenario:
  When we ask for the full name for "OXF"
  Then we are told it is "Oxford"
  
  Scenario:
  When we ask for the full name for "BNS"
  Then we are told it is "Birmingham New Street"


We then run that under cucumber, and we're offered snippets of code to help us implement the tests which might look like

  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


and when we run that completed code, all of our scenarios are run and we see a full set of results:

 munchkin:lr grahamellis$ cucumber -s bdd_stations
 Feature: Checking we know station names
 
   Scenario: 
     When we ask for the full name for "MKM"
     Then we are told it is "Melksham"
 
   Scenario: 
     When we ask for the full name for "PLY"
     Then we are told it is "Plymouth"
 
   Scenario: 
     When we ask for the full name for "OXF"
     Then we are told it is "Oxford"
 
   Scenario: 
     When we ask for the full name for "BNS"
     Then we are told it is "Birmingham New Street"
       
       expected: "Birmingham New Street"
            got: "Barnes"
       
       (compared using ==)
        (RSpec::Expectations::ExpectationNotMetError)
       ./bdd_stations/step_definitions/station_steps.rb:10:in `/^we are told it is "(.*?)"$/'
       bdd_stations/station.feature:19:in `Then we are told it is "Birmingham New Street"'
 
 Failing Scenarios:
 cucumber bdd_stations/station.feature:17
 
 4 scenarios (1 failed, 3 passed)
 8 steps (1 failed, 7 passed)
 0m0.238s
 munchkin:lr grahamellis$


Files for this example:
[here]for the file to be tested
[here] for feature definitions
[here] for step implementation
[here] for the data used by the class