Correcting your rcov report for untested code

I’ve used rcov for a long time to check the code coverage on my Ruby applications. Code coverage shows what parts of an application have not been tested. It can be abused if it’s used as an absolute metric (must be 99%+) but it’s great to see where fragile parts might be located. A problem I’ve had though, is rcov will not add a file to it’s report unless it has been loaded. This means if you just run rcov out of the box, you could get a high coverage report because the untested files are not counted.

After searching, I’ve found a post by Jamie Flournoy that had a simple chunk of code to require all Ruby files when rcov is run. I’ve adapted it for my Redmine plugins (Rails Engines) and it’s been really useful as I refactor the code.

1
2
3
4
if defined?(Rcov)
  all_app_files = Dir.glob('{app,lib}/**/*.rb')
  all_app_files.each{|rb| require rb}
end

All I had to do was to put this into my spec_helper.rb file and rerun rcov. Now the coverage report is loading the entire application correctly. If you want to see a more complex example, check out Jamie Flournoy’s original post where he filters out a file files.

Eric