Search code examples
cucumberbdd

Dynamic data in Cucumber tables


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.


Solution

  • 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!