Far Beyond Programming — Braindumps by Eric Teubert

Rails: How to combine Cucumber, RSpec and rcov

20 April 2011

This post is the missing documentation on how to create rcov results of both RSpec and Cucumber. There are some posts on the web already, but they are all outdated. I had to fiddle quite a bit to get everything to work. By the way, whenever I am in search for decent blogumentation, it is often hard to find out how up-to-date it is. I am trying hard to be of better service in this regard, so here is my toolbox:

The key idea to get rcov working with more than one testing library is its optional parameter --aggregate. This is the description from the help file:

--aggregate FILE    Aggregate data from previous runs
                    in FILE. Overwrites FILE with the
                    merged data. FILE is created if
                    necessary.

Perfect! Now all that is missing is a rake task to spare us all the tedious typing. Paste it directly into your Rakefile or into a separate file in lib/tasks.

require 'rspec/core/rake_task'
require 'cucumber/rake/task'

namespace :rcov do
  
  rcov_options = %w{
    --rails
    --exclude osx\/objc,gems\/,spec\/,features\/,seeds\/
    --aggregate coverage/coverage.data
  }
  
  Cucumber::Rake::Task.new(:cucumber) do |t|
    t.cucumber_opts = "--format pretty"
    
    t.rcov = true
    t.rcov_opts = rcov_options
  end

  RSpec::Core::RakeTask.new(:rspec) do |t|
    t.spec_opts = ["--color"]
    
    t.rcov = true
    t.rcov_opts = rcov_options
    t.rcov_opts += %w{--include views -Ispec}
  end
  
  desc "Run cucumber & rspec to generate aggregated coverage"
  task :all do |t|
    rm "coverage/coverage.data" if File.exist?("coverage/coverage.data")
    Rake::Task['rcov:rspec'].invoke
    Rake::Task["rcov:cucumber"].invoke
  end
end

Actually, there are three resulting rake tasks.

rake rcov:cucumber
rake rcov:rspec
rake rcov:all

The latter is the most important one. It runs both RSpec and Cucumber, generating a combined result. Just open coverage/index.html with your browser of choice and be excited about the pretty results.

Fork me on GitHub