Reputation: 5480
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?
Upvotes: 2
Views: 2706
Reputation: 1363
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
Upvotes: 1
Reputation: 11
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
Upvotes: 0
Reputation: 61
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
Upvotes: 0
Reputation: 788
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.
Upvotes: 1
Reputation: 31
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.
Upvotes: 3
Reputation: 312
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
Upvotes: 1
Reputation: 2864
The AfterStep
hook only receives the scenario as parameter.
What you can do, is count the steps, and then get the current one:
AfterStep do |scenario|
@step ||= 0
p scenario.steps[@step].name
@step += 1
end
This will print, in turn, the names of each parameter
Upvotes: 1