Formatters

Configurable colors

RSpec allows you to configure the terminal colors used in the text formatters.

  • failure_color: Color used when tests fail (default: :red)
  • success_color: Color used when tests pass (default: :green)
  • pending_color: Color used when tests are pending (default: :yellow)
  • fixed_color: Color used when a pending block inside an example passes, but was expected to fail (default: :blue)
  • detail_color: Color used for miscellaneous test details (default: :cyan)

Colors are specified as symbols. Options are :black:red:green,
:yellow:blue:magenta:cyan, and :white.Scenarios

  • @ansi

Customizing the failure colorGivena file named “custom_failure_color_spec.rb” with:

RSpec.configure do |config|
  config.failure_color = :magenta
  config.tty = true
  config.color = true
end

RSpec.describe "failure" do
  it "fails and uses the custom color" do
    expect(2).to eq(4)
  end
end

WhenI runĀ rspec custom_failure_color_spec.rb --format progressThenthe failing example is printed in magenta

JSON formatter

ScenariosFormatting example names for retryGivena file named “various_spec.rb” with:

RSpec.describe "Various" do
  it "fails" do
    expect("fail").to eq("succeed")
  end

  it "succeeds" do
    expect("succeed").to eq("succeed")
  end

  it "pends"
end

WhenI run rspec various_spec.rb --format jThenthe output should contain all of these:

“summary_line”:”3 examples, 1 failure, 1 pending”
“examples”:[
“description”:”fails”
“full_description”:”Various fails”
“status”:”failed”
“file_path”:”./various_spec.rb”
“line_number”:2
“exception”:{
“class”:”RSpec::Expectations::ExpectationNotMetError”

Andthe exit status should be 1

Custom formatters

RSpec ships with general purpose output formatters. You can tell RSpec which
one to use using the --format command line option.

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.ScenariosCustom formatterGivena file named “custom_formatter.rb” with:

class CustomFormatter
  # This registers the notifications this formatter supports, and tells
  # us that this was written against the RSpec 3.x formatter API.
  RSpec::Core::Formatters.register self, :example_started

  def initialize(output)
    @output = output
  end

  def example_started(notification)
    @output << "example: " << notification.example.description
  end
end

Anda file named “example_spec.rb” with:

RSpec.describe "my group" do
  specify "my example" do
  end
end

WhenI run rspec example_spec.rb --require ./custom_formatter.rb --format CustomFormatterThenthe output should contain “example: my example”Andthe exit status should be 0