Guide exercise to help you learn Gherkin, Cucumber and Rspec
Archive - Originally posted on "The Horse's Mouth" - 2015-01-06 20:16:48 - Graham EllisDuring today's Ruby course, I moved on to Cucumber and Gherkin very quickly - for a private course with delegates looking to using Behaviour Driven Development as the core of their work. Ruby's basics were covered first - variables, calculations, conditionals and loops. Then we moved on to functions, classes and methods. And by the afternoon of the second day, we were on to defining features in Gherkin:
Defining the steps used to test those features
1. Define the behaviour
Feature: Seeing how many can sit at a table
Scenario: Seeing numbers that can fit around each table
Given I have a table 1900 x 825 mm
When I ask how many people can sit at it with 850 mm each
Then I should be told 4
When I ask how many people can sit at it with standard space each
Then I should be told 6
Scenario: Seeing numbers that can fit around each table
Given I have a table 700 x 700 mm
When I ask how many people can sit at it with standard space each
Then I should be told 0
See tables.feature
2. Define the tests to implement that behaviour
(much of this automated from your first Cucumber run)
Given(/^I have a table (\d+) x (\d+) mm$/) do |arg1, arg2|
@centre = Table.new("Gill",11,arg1.to_i,arg2.to_i)
end
When(/^I ask how many people can sit at it with (\d+) mm each$/) do |arg1|
@bums = @centre.getSeats(arg1.to_i)
end
When(/^I ask how many people can sit at it with standard space each$/) do
@bums = @centre.getSeats
end
Then(/^I should be told (\d+)$/) do |arg1|
expect(@bums).to eq(arg1.to_i)
end
See table_steps.rb
3. Define the class to satisfy the tests
class Table
def initialize(waiter,number,mm1,mm2)
@waiter = waiter
@number = number
@mm1 = mm1
@mm2 = mm2
end
def getSeats(elbows = 800)
side1 = (@mm1 / elbows).to_i
side2 = (@mm2 / elbows).to_i
return 2 * (side1 + side2)
end
end
See tables.rb
Exercise for delegates - get the above code working on your training system and then implement code for the following extra scenario ( already provided, commented out in the feature file)
# Table cloths hang over by 10 cm and weigh 275 grams / square metre
# Scenario: Seeing how heavy a table cloth is
# Given I have a table 1900 x 825 mm
# When I ask how heavy the table cloth is
# Then I should be told the weight is 591.9375
The exercise here is an interesting one - we don't have delegates write a behariour, tests and class from scratch as that's a lot to take in for the first use. Rather, we have them take an example that we've gone through with them, then provide enhancements.
If you're learning Ruby on our Learning to Program in Ruby or Ruby Programming courses, I would be happy to extent into an introduction to Gherkin, Cucumber and Rspec for you.