Andrew Andrew - 6 months ago 14
Ruby Question

How to output Cucumber background steps before each scenario?

Normally, Cucumber will output background steps to look the same as you defined them in your feature file (once at the top).

$ 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


It would be much easier to see when a background step is executed successfully if you could always display the steps at the beginning of a scenario. How can I enable this behavior?

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

Answer

You will have to create a custom formatter.

Assuming you want something like the pretty formatter, you can create class that inherits from the pretty formatter and replaces the required methods. Basically, you would want to change the logic that:

  • The background is not displayed
  • Scenarios show their background steps

This formatter appears to work:

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

Assuming this is in your support folder, you can use it when start cucumber:

cucumber -f Cucumber::Formatter::MyFormatter
Comments