Rails, tests and code coverage

“If it’s not tested assume it’s broken.” This is one of the mantras in my company. Sometimes it’s easier said then done. If I always had to test everything I would be doing nothing but testing. So I employ different techniques to keep me programming and the computer to test the code I write.

One of the nice things about Rails is that you have a whole array of tools to automate testing and at least one very nice tool to let you know what’s tested and what’s not. Yes I am talking about Rcov.

Rcov has been “the bee’s knees” for code coverage awareness. Recently I have noticed Rcov has been doing more work then expected. When I ran the rcov command in a rails project it tested everything. I mean everything, including gems installed on the system.

Since everything is just a bit too much for my project I started looking for a way to limit the output. It appears I had to use -x option to stop the code coverage tool from traversing the gems. Here is the whole task:

desc 'Measures test coverage using rcov'
Rcov::RcovTask.new(:rcov) do |rcov|
  rcov.pattern    = "test/**/*_test.rb"
  rcov.rcov_opts  = [
    "-x 'gems/.*,rubygems/.*,rcov/.*'",
    "-T",
    "--rails" ]
  rcov.output_dir = "rcov/unified"
end

I hope this helps you.