I had a few mis-configuration issues when setting up shoulda and rcov for a new Rails 2.2.2 project, so I thought I’d jot down a few notes (mini tutorial, quickstart) to help save others from burning time on what should be a simple task.
shoulda is a library build on Test::Unit that provides helpers, macros and assertions to make testing easier.
rcov is a code coverage tool for Ruby.
1. Install rcov
sudo gem install rcov
2. Install shoulda
sudo gem install thoughtbot-shoulda --source=http://gems.github.com
3. Create your Rails project
rails myapp
4. Modify myapp/Rakefile
require(File.join(File.dirname(__FILE__), 'config', 'boot'))
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'
require 'shoulda/tasks'
namespace :test do
desc 'Measures test coverage'
task :coverage do
rm_f "coverage"
rm_f "coverage.data"
rcov = "rcov -Itest --rails --aggregate coverage.data -T -x \" rubygems/*,/Library/Ruby/Site/*,gems/*,rcov*\""
system("#{rcov} --no-html test/unit/*_test.rb test/unit/helpers/*_test.rb")
system("#{rcov} --no-html test/functional/*_test.rb")
system("#{rcov} --html test/integration/*_test.rb")
system("open coverage/index.html") if PLATFORM['darwin']
end
end
5. Modify myapp/test/test_helper.rb
... # Add the following line require 'shoulda/rails' # require 'shoulda' also worked ...
Conclusion
After you’ve written some shoulda tests, you should be able to use the following rake commands:
rake test rake test:units rake shoulda:list # display specs from shoulda tests rake test:coverage # run rcov and display code coverage
-
Are you sure everything is OK with the line that starts with “rcov = ” in your Rakefile? There seems to be a problem with the quotes (e.g., two ” marks at the end)?
Thanks, Ken
-
Thanks Brian for the quick tip .. It really helps.
One more adjustment to add, specially when u have models in namespaces which will result in test files in sub-directories under the test different paths (Unit and Functional).
I made these changes to paths in the task:
test/unit/**/*_test.rb
test/functional/**/*_test.rb
test/integration/**/*_test.rbinstead of
test/unit/*_test.rb
test/functional/*_test.rb
test/integration/*_test.rbThis began when I’ve noticed that RCov shows that some models and controllers are not well covered though I was sure they are properly covered. Then I discovered that all of these files are classes in namespaces with their test files in sub folders under the test/unit and test/functional.
This is also a problem with the “shoulda:list” task, as it skips such classes saying that they don’t map to a class.
-
Brian,
I know this post was 1 1/2 years ago, but it’s just what I needed. Thanks for the post. I’d like to ask for some tips on using rcov effectively. I’ll try to remember when I see you.
Best,
Michael

4 comments
Comments feed for this article
Trackback link: http://lojic.com/blog/2009/02/26/setup-shoulda-and-rcov-for-rails-222/trackback/