Jamie's Space

JP

Getting SimpleCov and Spork to Play Together

I have been using SimpleCov to measure the code coverage of my specifications, and it has been excellent. I would recommend it, if only for how easy it was to get it working with RSpec.

I have run into one problem though - running it under Spork generates no results! As far as I can tell, this is a problem with the way Spork caches your application files. SimpleCov uses the Ruby 1.9 built in profiling features, and either 1.9 or Spork need the files under inspection to be loaded after the profiling has started. Unfortunately your application files aren’t reloaded when you are using Spork, that’s kind of the point!

Some people seem to be able to get away with merely turning off application file caching in config/environments/test.rb, but that didn’t work for me. Instead, I have come up with a different solution: Only turn on code coverage reporting when I run RSpec outside of Spork. At the top of spec/spec_helper.rb I have the following block:

if(ENV["RUN_COVERAGE"])
  require 'simplecov'
  SimpleCov.start 'rails' do
    add_filter "/spec/"
  end
  puts "Running coverage tool\n"
end

That way I can run RUN_COVERAGE=true rspec spec/ in the root of my application directory, and RSpec will run with SimpleCov enabled. As an added bonus, the code coverage metrics aren’t running on every test run, so my tests are faster!