How can I figure out which step I've just exec

2019-02-15 14:54发布

I'm writing a method to be executed on the AfterStep callback for Cucumber.

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

How can I figure out which step was executed before this hook was called?

标签: ruby cucumber
7条回答
Ridiculous、
2楼-- · 2019-02-15 15:15

Using gem cucumber 2.1.0 and scenario outlines, the scenario object in "Afterstep" is just a test result status, it does not contain the name of the step. I had to use "Before" (called before the first step) that contains a test list.

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

The logger is required because 'puts' only display when the scenario outline ends.

查看更多
ら.Afraid
3楼-- · 2019-02-15 15:18

The API has been changed... Based on afterhook doc you can get the result (Cucumber::Core::Test::Result) and the step (Cucumber::Core::Test::Step) like this:

AfterStep do |result, test_step|
  #do something
end

You can get the step name with:

stepName = test_step.text

or

stepName = test_step.to_s
查看更多
来,给爷笑一个
4楼-- · 2019-02-15 15:20

Vince has a good solution, I would recommend a refactor:

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

You can use the @tests.count instead of the @count variable

I would have made this as comment but I don't have enough reputation yet.

查看更多
趁早两清
5楼-- · 2019-02-15 15:20

I worked it out as follows:

Before do |scenario|
    ...
    @scenario = scenario
    @step_count = 0
    ...
  end

  AfterStep do |step|
    @step_count += 1
  end

That keeps the step number updated. In order to get the step name:

@scenario.test_steps[@step_count].name
查看更多
地球回转人心会变
6楼-- · 2019-02-15 15:20

Vince's answer is great! and SMAG's refactor is cool ! but when I applied the solution on my cucumber test project, I got an error:

 undefined method `name' for #<Cucumber::Core::Test::Step:>

so, maybe the answer can update as below:

Before do |scenario|
    @tests = scenario.test_steps.map(&:text).delete_if { |text| text == 'AfterStep hook' }
end
查看更多
贼婆χ
7楼-- · 2019-02-15 15:25

Note:

The api has changed slightly. you now need to use 'to_a'

i.e. the Alex Siri's line above would be changed to:

  p scenario.steps.to_a[@step].name
查看更多
登录 后发表回答