Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic data in Cucumber tables

Tags:

cucumber

bdd

I have a Cucumber table, one of the fields is a date which I would like to have populated with todays date. Is there a way of doing this without having to hard code todays date into the table?

Basically I would like to enter Time.now.strftime("%Y-%m-%d") into the table and not have it break.

like image 776
KJF Avatar asked Oct 24 '09 12:10

KJF


3 Answers

Since the table is being processed by your step definition, you could put a special place holder in the table, such as the string "TODAYS_DATE", and then use map_column! to process the data in the column to the format you want.

For example given the following table

Given the following user records
  | username | date        |
  | alice    | 2001-01-01  |
  | bob      | TODAYS_DATE |

In your step definition you would have

Given /^the following user records$/ do |table|
  table.map_column!('date') do |date| 
    if date == 'TODAYS_DATE'
      date = Time.now.strftime("%Y-%m-%d")
    end
    date
  end
  table.hashes.each do |hash|
    #Whatever you need to do
  end
end

Note this only changes the values when you ask for the hash. table and table.raw will remain the same, but whenever you need the row hashes, they will be converted by the code within the map_column!

like image 67
Brandon Bodnar Avatar answered Oct 09 '22 09:10

Brandon Bodnar


I know it's been ages since this question was asked but I was doing something similar with Cucumber recently so here's an alternative solution if anyone's interested...

Given the following user records
 | username | date                             |
 | bob      | Time.now.strftime("%Y-%m-%d")    |

And then in your step definition just eval() the date string

Given /^the following user records$/ do |table|
  table.hashes.each do |hash|
    date = eval(hash["date"])
  end
end

Though unlike Brandon's example this wont let you put in exact dates as well without some further logic.

like image 38
Ganesh Shankar Avatar answered Oct 09 '22 08:10

Ganesh Shankar


bodnarbm's answer is pretty good if that is what you want to do. My own suggestion would be to take a look at the timecop gem. Use it to set time to a known day then adjust your tables accordingly.

like image 4
John F. Miller Avatar answered Oct 09 '22 10:10

John F. Miller