Pauline
Pauline

Reputation: 3836

Rspec documentation output format

According to this piece of documentation, it is possible to achieve the following output format by selecting the format documentation:

something
  does something that passes
  does something that fails (FAILED - 1)
  does something that is pending (PENDING: Not Yet Implemented)

Is it possible to slightly edit this so it outputs as:

something
  does something (SUCCESS)
  does something (FAIL)
  does something (PENDING)

Basically I would like the result of the test displayed no matter what - instead of just logging explicitly the failures and the pending ones.

Upvotes: 2

Views: 787

Answers (2)

htanata
htanata

Reputation: 36944

I was able to do this by subclassing RSpec::Core::Formatters::DocumentationFormatter. Create the following file as spec/formatters/custom_formatter.rb:

class CustomFormatter < RSpec::Core::Formatters::DocumentationFormatter
  RSpec::Core::Formatters.register self

  private

  def passed_output(example)
    format_output(example, 'SUCCESS', :success)
  end

  def pending_output(example, _message)
    format_output(example, 'PENDING', :pending)
  end

  def failure_output(example)
    format_output(example, 'FAILED', :failure)
  end

  def format_output(example, status_text, code_or_symbol)
    RSpec::Core::Formatters::ConsoleCodes.wrap(
      "#{current_indentation}#{example.description.strip} (#{status_text})",
      code_or_symbol
    )
  end
end

Then run the specs using this:

rspec --require formatters/custom_formatter --format CustomFormatter

Instead of --require formatters/custom_formatter, you can also require the formatter on spec/spec_helper.rb, e.g.

require_relative 'formatters/custom_formatter'

Then you only need to run this:

rspec --format CustomFormatter

If you want CustomFormatter to be the default formatter, you can add the command line options to .rspec configuration file at your project root. Here's how it should look like:

--require spec_helper

--require /path/to/custom_formatter.rb
--format CustomFormatter

With that, you no longer need to specify any command line arguments to use CustomFormatter.

Documentations and references:

Upvotes: 2

LazyNick7
LazyNick7

Reputation: 83

You can not change the existing RSpec formatters, but you can create your own

When RSpec's built-in output formatters don't, however, give you everything you need, you can write your own custom formatter and tell RSpec to use that one instead. The simplest way is to subclass RSpec's BaseTextFormatter, and then override just the methods that you want to modify.

Upvotes: 0

Related Questions