Monday, November 8, 2010

How to: write rcov test

'rcov' is a ruby test coverage tool which tells you how effective is the test by giving you the complete coverage of the test that you have written.

You can use it in any of your projects and check your test effectiveness.

First install the gem

$gem install rcov

Next generate the rcov documents like below

$rcov -I lib spec/*.rb --exclude ^spec,/gems/ -T --no-html

The above parameters tell rcov to include lib directory as well as all files inside spec dir and exclude all the gems.
Also, it displays the output in terminal and doesn't generate the html file. You can take the --no-html flag off if you like an interactive html view which is inside the coverage folder.

You can achieve the same with rake task also like below:

Include the 'rcov_custom' file in the rake file.

# In Rake
require File.expand_path(File.dirname(__FILE__) + '/lib/tasks/rcov_custom')

Next you write the following in the file.
# rcov_test.rb
desc "Custom rcov" do |t|
t.rcov = true
t.rcov_opts = %w{--exclude gems\/,spec\/ -T}

In terminal, check the rake tasks.

$Rake -T

You should see a custom rake task named 'Custom rcov'.
Finally, generate the rcov test whenever you feel like with the rake command.

$rake rcov_custom

Hope your code is 100% covered up by your test. :)