【发布时间】:2014-01-03 21:19:04
【问题描述】:
我正在为 Cucumber 编写一个在 AfterStep 回调上执行的方法。
https://github.com/cucumber/cucumber/wiki/Hooks#step-hooks
如何确定在调用此钩子之前执行了哪个步骤?
【问题讨论】:
我正在为 Cucumber 编写一个在 AfterStep 回调上执行的方法。
https://github.com/cucumber/cucumber/wiki/Hooks#step-hooks
如何确定在调用此钩子之前执行了哪个步骤?
【问题讨论】:
使用 gem cucumber 2.1.0 和场景大纲,“Afterstep”中的场景对象只是一个测试结果状态,它不包含步骤的名称。我必须使用包含测试列表的“之前”(在第一步之前调用)。
require 'logger'
$logger = Logger.new(STDOUT)
Before do |scenario|
@count = 0
@tests = Array.new
scenario.test_steps.each{|r|
if( r.name != "AfterStep hook")
@tests << r
end
}
end
AfterStep do |scenario| # run after each step
$logger.info(@tests[@count].name.green)
@count += 1;
end
需要记录器,因为“puts”仅在场景大纲结束时显示。
【讨论】:
AfterStep 挂钩仅接收场景作为参数。
你可以做的,就是计算步数,然后得到当前的步数:
AfterStep do |scenario|
@step ||= 0
p scenario.steps[@step].name
@step += 1
end
这将依次打印每个参数的名称
【讨论】:
p Array(scenario.scenario_outline.send(:steps))[@step].name
注意:
api 略有变化。你现在需要使用'to_a'
即上面的 Alex Siri 行将更改为:
p scenario.steps.to_a[@step].name
【讨论】:
Vince 有一个很好的解决方案,我会推荐一个重构:
Before do |scenario|
@tests = scenario.test_steps.map(&:name).delete_if { |name| name == 'AfterStep hook' }
end
您可以使用@tests.count 代替@count 变量
我会将此作为评论,但我还没有足够的声誉。
【讨论】:
API 已更改...基于afterhook doc,您可以获得result (Cucumber::Core::Test::Result) 和step (Cucumber::Core::Test::Step) 像这样:
AfterStep do |result, test_step|
#do something
end
您可以通过以下方式获取步骤名称:
stepName = test_step.text
或
stepName = test_step.to_s
【讨论】:
我是这样计算的:
Before do |scenario|
...
@scenario = scenario
@step_count = 0
...
end
AfterStep do |step|
@step_count += 1
end
这会保持步数更新。为了获得步骤名称:
@scenario.test_steps[@step_count].name
【讨论】:
文斯的回答很棒! SMAG 的重构很酷!但是当我将解决方案应用于我的黄瓜测试项目时,出现错误:
undefined method `name' for #<Cucumber::Core::Test::Step:>
所以,也许答案可以更新如下:
Before do |scenario|
@tests = scenario.test_steps.map(&:text).delete_if { |text| text == 'AfterStep hook' }
end
【讨论】: