如何在每个方案之前输出黄瓜背景步骤



通常,Cucumber 将输出背景步骤,看起来与您在功能文件中定义它们相同(一次位于顶部)。

$ bundle exec cucumber --color --format pretty
Feature: Something
  Background:
    Given step 1
    And step 2
  Scenario: a scenario
    When I do step 3
    Then it works
  Scenario: another scenario
    When I do a different step 3
    Then it works

如果始终可以在方案开始时显示后台步骤,则在成功执行后台步骤时会容易得多。如何启用此行为?

Feature: Something
  Scenario: a scenario
    Given step 1
    And step 2
    When I do step 3
    Then it works
  Scenario: another scenario
    Given step 1
    And step 2
    When I do a different step 3
    Then it works

您必须创建自定义格式化程序。

假设你想要类似漂亮的格式化程序的东西,你可以创建继承自漂亮格式化程序并替换所需方法的类。基本上,您需要更改以下逻辑:

  • 不显示背景
  • 方案显示其背景步骤

此格式化程序似乎有效:

require 'cucumber/formatter/pretty'
module Cucumber
  module Formatter
    class MyFormatter < Pretty
      def background_name(keyword, name, file_colon_line, source_indent)        
        # Do nothing
      end
      def before_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background, file_colon_line)
        @hide_this_step = false
        if exception
          if @exceptions.include?(exception)
            return
          end
          @exceptions << exception
        end
        if @in_background
          @hide_this_step = true
          return
        end
        @status = status
      end
    end # MyFormatter
  end # Formatter
end # Cucumber

假设这在您的支持文件夹中,您可以在启动黄瓜时使用它:

cucumber -f Cucumber::Formatter::MyFormatter

在撰写本文时,接受的解决方案在当前版本的 Cucumber 2.3.3 中不起作用。后台步骤永远不会进入before_step_result。这是我为这个版本的黄瓜找到的最佳解决方案:

将方法Cucumber::Formatter::LegacyApi::Adapter::FeaturePrinter. same_background_as_previous_test_case?(在黄瓜宝石的lib/cucumber/formatter/legacy_api/adapter.rb中定义)从

def same_background_as_previous_test_case?(source)
  source.background == @previous_test_case_background
end

def same_background_as_previous_test_case?(source)
  false
end

由于FeaturePrinter是动态定义的,因此无法通过在 features/support 中的文件中定义新方法来对其进行猴子修补。您需要分叉 Gem,或者,如果您只需要偶尔进行此更改以进行调试,请在已安装的 gem 副本中编辑该文件。

最新更新