我怎么能弄清楚我刚刚在Cucumber的AfterStep钩子中执行了哪一步?

我正在编写一个在Cucumber的AfterStep回调上执行的方法。

https://github.com/cucumber/cucumber/wiki/Hooks#step-hooks

如何在调用此挂钩之前确定执行了哪个步骤?

AfterStep挂钩仅接收方案作为参数。

你能做什么,是计算步骤,然后得到当前的步骤:

 AfterStep do |scenario| @step ||= 0 p scenario.steps[@step].name @step += 1 end 

这将依次打印每个参数的名称

使用gem cucumber 2.1.0和场景轮廓,“Afterstep”中的场景对象只是一个测试结果状态,它不包含步骤的名称。 我不得不使用包含测试列表的“Before”(在第一步之前调用)。

 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”仅在场景大纲结束时显示。

注意:

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变量

我会把它作为评论,但我还没有足够的声誉。

我按如下方式解决了这个问题:

 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 # 

所以,答案可能会更新如下:

 Before do |scenario| @tests = scenario.test_steps.map(&:text).delete_if { |text| text == 'AfterStep hook' } end 

API已被更改…基于afterhook文档,你可以得到结果 (Cucumber :: Core :: Test :: Result)和步骤 (Cucumber :: Core :: Test :: Step),如下所示:

 AfterStep do |result, test_step| #do something end 

您可以使用以下命令获取步骤名称:

 stepName = test_step.text 

要么

 stepName = test_step.to_s