【问题标题】:Pull scenario outline (or read a tag) from within cucumber step从黄瓜步骤中提取场景大纲(或读取标签)
【发布时间】:2013-08-21 18:25:16
【问题描述】:

如果我有一个这样开始的场景:

  @my-tag

  Scenario Outline:
  Admin user changes email

    Given I register a random email address

...

是否可以在单个步骤定义中读取场景大纲文本或@my-tag?例如,在I register a random email address 步骤中,如果它在给定场景或标签值下运行,我想打印调试信息。

【问题讨论】:

  • 好问题,谢谢

标签: ruby cucumber


【解决方案1】:

您无法直接从步骤定义中访问该信息。如果您需要这些信息,则必须在 before hook 期间捕获它。

黄瓜 v3+

下面的 before 钩子将捕获功能名称、场景/大纲名称和标签列表。请注意,此解决方案适用于 Cucumber v3.0+。对于早期版本,请参见答案的末尾。

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

以特征文件为例:

@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     |

步骤定义为:

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

会给出结果:

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

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

然后您可以检查@scenario_name 或@scenario_tags 的条件逻辑。

黄瓜 v2

对于 Cucumber v2,所需的钩子更复杂:

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

输出略有不同:

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

"Feature description"
"Outline description"
["@outline_tag", "@feature_tag"]

【讨论】:

  • 只是添加:scenario.feature.source_tag_names 将只返回 ["@feature_tag"]
  • uninitialized constant Cucumber::Ast。 Ast 已被弃用,无法追踪如何替换它。
  • @MichaelJohnston,答案已针对 Cucumber v3 更新。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多