Skip to content

rcov and rails

rcov and Rails
I had the good fortune of attending Rails Conf recently on behalf of the consulting company I work for, Asynchrony Solutions. One of the topics at the great Refactotem tutorial (hosted by the guys from Relevance) was rcov, a code coverage tool for Ruby. One of the things I missed in, or was neglected from, the talk was how to actually run coverage tasks against Rails. So I thought I would share the code to make the test:coverage task that I found with some digging.

Add the following to the Rakefile in the root of your rails app:

require 'rcov/rcovtask'

namespace :test do
namespace :coverage do
desc "Delete aggregate coverage data."
task(:clean) { rm_f "" }
desc 'Aggregate code coverage for unit, functional and integration tests'
  task :coverage => "test:coverage:clean"
    %w[unit functional integration].each do |target|
    namespace :coverage do do |t|
      t.libs << "test"
      t.test_files = FileList["test/#{target}/*_test.rb"]
      t.output_dir = "test/coverage/#{target}"
      t.verbose = true
      t.rcov_opts << '--rails --aggregate'
  task :coverage => "test:coverage:#{target}"

You can then run rcov on your rails app by running:

rake test:coverage

After this completes, it will output index.html files in RAILS_ROOT/tests/coverage/[units, functional, integration]. There is no overall index file, as, if you read the rake task, it is running rcov separately for each of [units, functional, integration].

Rcov has a few things to work out like showing untested code in modules sometimes, but otherwise it gives you a good idea of sections and branches of your code that are not tested. It’s very easy to set up so why not give it a try. But remember, metrics can only help point out problem spots in your code, they are not a replacement for good coding techniques.

One Comment