Lokesh Lokesh - 5 months ago 26
Ruby Question

Print only the number of failed examples with rspec

Is there a way to make

rspec
just print number of failed examples without any other information?

I want the output to be like this:

Finished in 2.35 seconds (files took 7.33 seconds to load)
1207 examples, 40 failures, 15 pending


Thank You

Answer

Out of the box RSpec does not have a formatter that matches the output you want. However, it is possible to write your own formatter.

Here's is what it would look like for RSpec 3+

RSpec::Support.require_rspec_core "formatters/base_text_formatter"

class SimpleFormatter < RSpec::Core::Formatters::BaseTextFormatter
  RSpec::Core::Formatters.register self, :example_passed, :example_pending, :example_failed, :dump_pending, :dump_failures, :dump_summary

  def example_passed(message)
    # Do nothing
  end

  def example_pending(message)
    # Do nothing
  end

  def example_failed(message)
    # Do nothing
  end

  def dump_pending(message)
    # Do nothing
  end

  def dump_failures(message)
  end

  def dump_summary(message)
    colorizer = ::RSpec::Core::Formatters::ConsoleCodes

    output.puts "\nFinished in #{message.formatted_duration} " \
       "(files took #{message.formatted_load_time} to load)\n" \
       "#{message.colorized_totals_line(colorizer)}\n"
  end
end

# Example from RSpec Core - https://github.com/rspec/rspec-core/blob/bc1482605763cc16efa55c98b8da64a89c8ff5f9/lib/rspec/core/formatters/base_text_formatter.rb

Then from the command line run rspec spec/ -r ./path/to/formatter -f SimpleFormatter.

To avoid having to type out the -r and -f options constantly, you can place them in your .rspec

--require ./path/to/formatter
--format SimpleFormatter

Now just running rspec spec/ will automatically use the formatter we just created.

Comments