Monday, 1 July 2013

Code Coverage with SimpleCov


Recently I have been using SimpleCov to test my code coverage. When UI first tried to use it, it threw up errors, but having updated the infrastructure, it seems to work fine (though I do get a ton of warnings). Just so you know, I am using JRuby 1.7.4 and Rails 3.2.13 - not sure which of these was causing the problem.

To get coverage statistics, install the SimpleCov gem, and put it in the gemfile.

group :test do
  gem 'simplecov'
end

In your test/test_helper file require it. Here I require it only if COVERAGE is set in the command line:

require 'simplecov' if ENV["COVERAGE"]

Then set some parameters in that file too. Here I exclude some folders and files, and then tell SimpleCov to group results (again, only if that command line flag is set).

SimpleCov.start do
  add_filter 'test/'
  add_filter 'config/'
  add_filter 'vendor/'
  add_filter 'mod_db.rb'  # One use methods for modifying the database

  add_group 'Controllers', 'app/controllers'
  add_group 'Models', 'app/models'
  add_group 'Helpers', 'app/helpers'
  add_group 'Mailers', 'app/mailers'
  add_group 'Views', 'app/views'
  add_group 'Library', 'lib/my_lib'
end if ENV["COVERAGE"]

It is slower than normal testing, so check that everything passes first. I use this on my command line, so err.txt catches all the warnings.

jruby -S rake test COVERAGE=true 2>err.txt >tmp.txt

The results appear in coverage/index.html, and look like this:



 Clicking on a file name will bring up that file, and any untested lines will be highlighted in red. I found a few places when a page should show a record and a set of associated sub-records, but the code for the associated was missed because I had not set the record to have any sub-records in my test.