如何在每个场景之前输出黄瓜后台步骤?

通常,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 

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

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

  • 不显示背景
  • 场景展示了他们的背景步骤

这个格式化似乎工作:

 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中找到的最佳解决方案:

更改方法Cucumber::Formatter::LegacyApi::Adapter::FeaturePrinter. same_background_as_previous_test_case? (在黄瓜gem的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副本中编辑该文件。