Skip to content

Instantly share code, notes, and snippets.

@iain
Created June 25, 2011 10:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iain/1046345 to your computer and use it in GitHub Desktop.
Save iain/1046345 to your computer and use it in GitHub Desktop.
RSpec Formatter to load SimpleCov

SpecCoverage formatter

This formatter loads SimpleCov a code coverage reporting tool for Ruby 1.9. SimpleCov already does a good job in making it really easy to configure and load itself, but even good efforts can be improved upon.

The only problem is that you'll need to have something like a spec_helper to load it. You might not have this or you might find it ugly having to resort to environment variables to turn it off or on.

With this formatter, SimpleCov will start, and it will load a .coverage file in which you can add ruby code to configure SimpleCov in a non-obtrusive way. Configuration for a typical Rails app will look like this:

SimpleCov.start 'rails'

To run this formatter, place it somewhere in your load path (like inside your spec directory).

This formatter doesn't have any output, so you'll probably want to add another formatter. I prefer the documentation (if the number of specs is limited) or Fuubar formatter (for big spec suites):

rspec spec -f SpecCoverage -f Fuubar

If you are using bundler, then don't forget to add simplecov to your Gemfile:

gem 'simplecov', :group => :test, :require => false

More information on SimpleCov can be found here.

require 'rspec/core/formatters/base_formatter'
require 'simplecov'
# This formatter does nothing else but run SimpleCov. That means that if you run this formatter on
# its own, you won't get any output. It is advised to add your favorite formatter, like this, to see
# test failures and so on:
#
# rspec spec -f SpecCoverage -fd
#
class SpecCoverage < ::RSpec::Core::Formatters::BaseFormatter
def initialize(*)
super
add_default_filter
load_simplecov_config
start_simplecov
end
private
# This is an RSpec filter, so we can safely assume that specs should be ignored
def add_default_filter
SimpleCov.add_filter '/spec/'
end
# Load a local .coverage file, to customize it yourself
#
# Example contents of this file:
#
# SimpleCov.start do
# add_filter '/foo/'
# end
#
# Rails users might want to add at least something like:
#
# SimpleCov.start 'rails'
#
def load_simplecov_config
load config_file if config_exists?
end
def config_exists?
File.exist?(config_file)
end
def config_file
File.expand_path(".coverage", SimpleCov.root)
end
# If you didn't start SimpleCov in your .coverage file, start it now
def start_simplecov
SimpleCov.start unless SimpleCov.running
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment