Rails 3 + Rcov Test Coverage

ruby-256

For the first time in a long time I added a new category to the blog. The new category is “Ruby/Rails Test Coverage” .

Writing tests is simple, but I wanted to make sure I had good coverage. This led to me to rcov which does a good job of running my tests and showing me a nice HTML output of the coverage. It was still a pain to go and run rcov and hunt down the report .

So I did some searching and ran across a nice rake plugin called rails rcov that does it all for me. Now I can run rake test:test:rcov from TextMate and see all my tests run and view my coverage.

I created the following rake file in lib/tasks/coverage.rake:

namespace :coverage do

task :clean do
rm_f “test/coverage”
rm_f “test/coverage.data”
Rcov = “cd test && rcov –rails –aggregate coverage.data -Ilib \
–text-summary -x ‘bundler/*,gems/*'”
end

def display_coverage
system(“sensible-browser test/coverage/index.html”)
end

desc ‘Measures unit test coverage’
task :unit => :clean do
system(“#{Rcov} –html unit/*_test.rb”)
display_coverage
end

desc ‘Measures functional test coverage’
task :func => :clean do
system(“#{Rcov} –html functional/*_test.rb”)
display_coverage
end

desc ‘All unit test coverage’
task :all => :clean do
system(“#{Rcov} –html */*_test.rb”)
display_coverage
end

end

task :coverage do
Rake::Task[“coverage:all”].invoke

end

This creates the following rake tasks you might be interested in:

coverage:unit – runs coverage on tests in test/unit

coverage:func – runs coverage on tests in test/functional

coverage:all – runs all unit tests

coverage – synonym for coverage:all

Note that the */*_test.rb syntax may not work depending on your shell.

Of course, you need rcov, so I added the following to my Gemfile:

gem ‘rcov’

Do a bundle install, and you should be able to run rake coverage. After running coverage, this script will automatically open your web browser to look at your coverage; It should look something like this, hopefully with more green bars than my just-getting-started project:

 

Happy Coding.

Total Page Visits: 2230 - Today Page Visits: 1

Leave a Reply