RCov - Code Coverage in Rails

If you haven’t been doing test driven development, and you should be, you may not be sure how well tested your rails application is. You can use rake stats to get your code to test ratio, but that only gives you a general sense of how you’re doing, but just knowing that your ratio is 1.0 to .7 doesn’t really ensure anything. You can write some tests in one line that test dozens of lines of code fairly well.

This is where using rcov comes in to save the day. Thankfully Coda Hale has written a rails plugin to make running rcov on your projects super easy. The instructions on his page tell you to install rcov by downloading it, but there’s a prepackaged gem that makes installation even easier. Let’s install it:

gem install rcov

Now Coda Hale recommends installing the plugin using -x to add and svn:externals entry, but I can’t stand having svn:externals since every time I want to update or commit I become dependent on someone else’s svn repository. You’re better off using piston if you need to keep your plugins up to date. So go ahead and run:

ruby script/plugin install http://svn.codahale.com/rails_rcov

Now you’re pretty much done for installing. Just run rake with a little change

rake test:units:rcov

You’ll now find a folder in your rails project called coverage. Look in there and find the index file and open it up. You now can see how well covered all your models are. If you open the individual model coverage file you can see exactly which lines aren’t covered and begin writing tests for them. There’s other options you can pass to rcov too, so take a look at the documentation if you want to get fancy. The only other command I run is

rake test:functionals:rcov RCOV_PARAMS="--sort=coverage"

So the difference there is I’m testing the controllers with functionals instead of the models with units and sorting the output by code coverage. This way I can easily see the models and controllers I need to do the most work on.