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 "coverage.data" }
end
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
      Rcov::RcovTask.new(target) 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 coverage.data'
    end
  end
  task :coverage => "test:coverage:#{target}"
  end
end

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

  1. pjammer wrote:

    Hey, is this rake task addition supposed to output all of the rails gems i use too? seems odd if it is, as i thought it’d only give me the test/**/*_test.rb files.

    Tuesday, January 5, 2010 at 8:53 am | Permalink

Post a Comment

Your email is never published nor shared.