Question

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.

Was it helpful?

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!

OTHER TIPS

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.

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.

Based on fixtures files I created this code:

Feature:

Given the following "Inquirers":
  | id | email                    | start_date        |
  |  1 | alberto@deco.proteste.pt | <%= Time.now %>   |

Helper:

Given(/^the following "(.*?)":$/) do |model, table|
  table.hashes.each do |hash|
    attributes = Rack::Utils.parse_nested_query(hash.to_query)
    object     = model_name.classify.constantize.new

    attributes.keys.each do |key|
      object.send("#{key}=", ERB.new(value).result())
    end
    ...
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top