RCov
RSpec has tight integration with RCov, the excellent code coverage tool for Ruby.
Running specs with RCov
The easiest way to use RCov with RSpec is from a rake script (Rakefile), using RSpec’s
Rake task. The snippet below is from RSpec’s own Rakefile.
require 'rake' require 'spec/rake/spectask' desc "Run all examples with RCov" Spec::Rake::SpecTask.new('examples_with_rcov') do |t| t.spec_files = FileList['examples/**/*.rb'] t.rcov = true t.rcov_opts = ['--exclude', 'examples'] end
By adding rcov=true to the rake task, specs will be run with RCov
instead of the standard ruby interpreter, and a coverage report like
this will be generated with the following command line:
rake examples_with_rcov
Also, because you don’t want your example files to be included in the coverage report (you just
want them to run), don’t forget to add t.rcov_opts = ['--exclude', 'examples']. You
can use this to exclude any other files that must be required but should not be measured (just
use a comma separated list).
Coverage threshold
You can guard your codebase’s coverage from dropping below a certain threshold
by using RSpec’s built-in task for verification of the total RCov coverage.
(This is not the same as RCov’s —threshold option, which is a filtering mechanism).
require 'rake' require 'spec/rake/verify_rcov' RCov::VerifyTask.new(:verify_rcov => 'spec:rcov') do |t| t.threshold = 100.0 t.index_html = 'coverage/index.html' end
This will give you a :verify_rcov task that will fail your build if the
coverage drops below the threshold you define.
If it’s too low you’re encouraged to write more specs rather than “fix”
the threshold value (which should usually only be adjusted upwards).
In fact, the task will also fail the build if the coverage raises above the threshold as well.
This might seem a bit counterintuitive, but this is when you should go and raise the
threshold in your Rakefile. This way you won’t miss temporary coverage increases. Crank it up!
This is how we got to 100% coverage for RSpec.
See RCov::VerifyTask for details.