I find it really useful to use a coverage tool when writing code. I don’t depend on it, but I do like to see what percentage of lines are covered, so I can at least catch any glaring misses.
In Ruby 1.8, we had rcov, which was (and is) a really great tool. In Ruby 1.9, I’ve been depending on SimpleCov. I really enjoy their reporter interface, and the usage is very similar to rcov. In your
spec_helper, before you include the thing you’re testing, just start up SimpleCov. I prefer to write it like:
begin require 'simplecov' SimpleCov.start rescue LoadError puts 'Coverage disabled, enable by installing simplecov' end require 'your_library' # your library require 'config/environment.rb' # rails?
Some features I really like:
Most times, I want to be able to see coverage for one test really clearly. For the past few weeks, I’ve been using something like this to accomplish it in my Rails projects:
filter = if ENV['COV'] == '*' lambda do |source| source.filename.start_with? File.join(Rails.root, 'spec/') end else paths = ENV['COV'].split(',').map do |rel| File.join(Rails.root, rel) end lambda do |source| !paths.include?(source.filename) end end # Apply SimpleCov.start do add_filter(&filter) end
That way, when starting
rspec (or spork, which I highly recommend), I can say what files I want to see coverage for. Another way to accomplish this which may suite you better is to create groups for things specified in COV.
If you’re not currently using SimpleCov, try it out!