Simplecov – Measure coverage in Rails

Today I spent some hours to discover how to measure Rails application’s test coverage, found Rcov and Simplecov gems. Rcov is not supported in Rails 3.2, while Simplecov is not supported using Ruby Enterprise Edition, so after burning some neurons I’ve upgraded ruby to 1.9.3 to use Simplecov rather. It is simple, but I spended many hours to configure it, so I would share with you some issues:

Haven’t you got any coverage reports? Have you got the following strange result?

Coverage report generated for RSpec to /path/doc/coverage. 0 / 0 LOC (0.0%) covered.

Check the following steps:

  1. You’ve added :require => false in your Gemfile!
    1
    
    gem 'simplecov', :require => false
    gem 'simplecov', :require => false
  2. You’ve included the simplecov module and started before any require statement in your spec_helper.rb or test_helper.rb!
    1
    2
    3
    4
    5
    6
    7
    8
    
    require 'simplecov'
    SimpleCov.start 'rails'
     
    # This file is copied to spec/ when you run 'rails generate rspec:install'
    ENV["RAILS_ENV"] ||= 'test'
    require File.expand_path("../../config/environment", __FILE__)
    require 'rspec/rails'
    require 'rspec/autorun'
    require 'simplecov'
    SimpleCov.start 'rails'
    
    # This file is copied to spec/ when you run 'rails generate rspec:install'
    ENV["RAILS_ENV"] ||= 'test'
    require File.expand_path("../../config/environment", __FILE__)
    require 'rspec/rails'
    require 'rspec/autorun'
  3. You’ve called the SimpleCov.start 'rails'

Little trick to generate the simplecov-html result to doc/coverage from any directory of your app, place these lines after the require section:

1
2
SimpleCov.root Rails.root
SimpleCov.coverage_dir "doc/coverage"
SimpleCov.root Rails.root
SimpleCov.coverage_dir "doc/coverage"

Now you just need to run rake spec or rake test, and there is your coverage report.