Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull scenario outline (or read a tag) from within cucumber step

Tags:

ruby

cucumber

If I have a scenario that starts like this:

  @my-tag

  Scenario Outline:
  Admin user changes email

    Given I register a random email address

...

is it possible to read either the scenario outline text or the @my-tag in an individual step definition? For example, in the I register a random email address step I'd like to print debug info if it's running under a given scenario or a tag value.

like image 795
larryq Avatar asked Aug 21 '13 18:08

larryq


1 Answers

You cannot access that information directly from within a step definition. If you need the information, you will have to capture it during a before hook.

Cucumber v3+

The following before hook will capture the feature name, scenario/outline name and the list of tags. Note that this solution is for Cucumber v3.0+. For earlier versions, see the end of the answer.

Before do |scenario|
  # Feature name
  @feature_name = scenario.feature.name

  # Scenario name
  @scenario_name = scenario.name

  # Tags (as an array)
  @scenario_tags = scenario.source_tag_names
end

As an example, the feature file:

@feature_tag
Feature: Feature description

  @regular_scenario_tag
  Scenario: Scenario description
    Given scenario details

  @outline_tag
  Scenario Outline: Outline description
    Given scenario details
    Examples:
      |num_1  | num_2  | result |
      | 1        |   1       |   2     |

With step defined as:

Given /scenario details/ do
     p @feature_name
     p @scenario_name
     p @scenario_tags
end

Will give the results:

"Feature description"
"Scenario description"
["@feature_tag", "@regular_scenario_tag"]

"Feature description"
"Outline description, Examples (#1)"
["@feature_tag", "@outline_tag"]

You could then check the @scenario_name or @scenario_tags for your conditional logic.

Cucumber v2

For Cucumber v2, the required hook is a more complicated:

Before do |scenario|
  # Feature name
  case scenario
    when Cucumber::Ast::Scenario
      @feature_name = scenario.feature.name
    when Cucumber::Ast::OutlineTable::ExampleRow
      @feature_name = scenario.scenario_outline.feature.name
  end

   # Scenario name
  case scenario
    when Cucumber::Ast::Scenario
      @scenario_name = scenario.name
    when Cucumber::Ast::OutlineTable::ExampleRow
      @scenario_name = scenario.scenario_outline.name
   end

  # Tags (as an array)
  @scenario_tags = scenario.source_tag_names
end

The output is slightly different:

"Feature description"
"Scenario description"
["@regular_scenario_tag", "@feature_tag"]

"Feature description"
"Outline description"
["@outline_tag", "@feature_tag"]
like image 117
Justin Ko Avatar answered Oct 13 '22 00:10

Justin Ko