0

How to prepare cucumber with tables in Ruby

Reading Time: 1 minute

TL;DR

In this post I will explain how to handle cucumber tables in the “Do not repeat yourself [source]” principle.

Data Tables are handy for passing a list of values to a step definition:

Given the following users exist:
 | name | email | twitter |
 | Aslak | aslak@cucumber.io | @aslak_hellesoy |
 | Julien | julien@cucumber.io | @jbpros |
 | Matt | matt@cucumber.io | @mattwynne |

Here is my first take how to index that data that was not DRY:

class UserListPage
 include PageObject
  data_map = {'name => 1, 'email' => 2, 'twitter' => 3}
  div(:name, :id => 'name')
  div(:email, :id => 'email')
  div(:twitter, :id => 'twitter')
end

And using that data_map in step definition:

Given /^the following users exist:$/ do |table|
data = table.raw[1]
data.shift
on UserListPage do |page|
  data.each {|row|
    expect(page.name).to eq row[page.data_map['name']]
    expect(page.email).to eq row[page.data_map['email']]
    expect(page.twitter).to eq row[page.data_map['twitter']]
  end
end

There is no need for data_map attribute, because table object already has this data. Dry version:

Given /^the following users exist:$/ do |table|
data = table.raw[1]
header = table.raw[0]
data.shift
on UserListPage do |page|
  data.each {|row|
    expect(page.name).to eq row[header.index('name')]
    expect(page.email).to eq row[header.index('email')]
    expect(page.twitter).to eq row[header.index('twitter')]
  end
end

And do not forget to remove data_map attribute from page object class.

Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Karlo Smid

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.