我有一个黄瓜表,其中一个字段是我希望填充今天日期的日期。 有没有办法做到这一点,而无需硬编码今天的日期到表中?

基本上我想在表格中输入 Time.now.strftime("%Y-%m-%d“),而不是让它中断。

有帮助吗?

解决方案

由于您的步骤定义正在处理表,您可以在表中放置一个特殊的占位符,例如字符串“TODAYS_DATE”,然后使用 map_column!来处理数据在列中您想要的格式。

例如,如下表所示

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

在您的步骤定义中,您将拥有

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

请注意,这只会在您请求哈希时更改值。 table和table.raw将保持不变,但只要你需要行哈希,它们就会被map_column中的代码转换!

其他提示

我知道自问这个问题以来已经很久了,但我最近和Cucumber做了类似的事情,所以如果有人有兴趣,这里有另一种解决方案......

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

然后在你的步骤定义中只需eval()日期字符串

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

虽然不像布兰登的例子,但是如果没有进一步的逻辑,这也不会让你输入确切的日期。

bodnarbm的答案非常好,如果这是你想要做的。我自己的建议是看看 timecop gem 。使用它将时间设置为已知日期,然后相应地调整表格。

基于fixtures文件,我创建了这段代码:

<强>功能

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

<强>助手:

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top