Search Courses

Search Courses
Home / Blog
Ruby Cucumber: Reuse step definition

Ruby Cucumber: Reuse step definition

Posted on : 16,Dec 2015 1409

If you are using ruby cucumber for test automation , you might be familiar to writing lot of step definition for similar task. For e.g. I work in a data project where we run different batch jobs, copy lot of files to different path and so on. My typical feature file look like

Scenario : Check if sales data is summarized
Given sales data is available
When the batch load data
Then summarized sales data is available

My another scenario looks like

Scenario : Check if commission data is summarized
Given commission data is available
When the batch load data
Then summarized commission data is available

If you look above examples , you will see a pattern. My arrange step looks for availability of row data, my act step runs a batch/job and my assert step verify data after loading.So when I write step definition , I am forced to write 6 steps.

Here I am showing a way to avoid writing repeated step definition for similar tasks. I am using a nice feature in ruby cucumber to parametrize certain values and have a single step definition to handle multiple scenario. I am trying to parametrize the "job" which needs to be run and with a single step definition running multiple jobs.

My feature file looks like below. I am using a data table to list all jobs. Then in my when step, I am running job 1 and then job2.

Scenario: Avoid multiple step definition for same job
    Given the following job exist:
      | JOB  |
      | JOB1 |
      | JOB2 |
    When I am in JOB1 task
    When I am in JOB2 task

In Step definition all you need is 

Given(/^the following job exist:$/) do |table|
  puts 'listing all jobs'
  puts table
end

When /^I am in (.*) task$/ do |job|
  puts 'Job I am going to run is '+job
end

Results:



The same logic can be used for common steps you do in your project. For e.g. log in with "User" , Search for an "account number" , push a particular "file" etc. This approach helps in maintaining  lesser/better code.   


Join the discussion

Improve the thread with your input and questions.
Carl Usmov
Consultant at IT Synergy Inc

Member Since : Dec, 2012

San Francisco California

Ruby Cucumber is an open source test automation tool which is used in BDD (Behaviour Driven Developm

Take course on


Interested in Ruby-Cucumber? We will notify you when knowledge is shared.