Code Coverage for Ruby on Rails Projects

Rodrigo Souza
Rodrigo Souza
February 24, 2023

We know that having tests covering our code base is always a relief. Code coverage is an important metric for any software project. It helps us to make our code more reliable. But how can we follow the progress of the code coverage in our Ruby on Rails projects? That is the subject of this article.

Widely adopted in the Ruby (and Rails) community, the Simplecov gem is a code coverage analysis tool for Ruby that measures and builds an interesting report about the current test coverage status for the files of one project.

Installation and Setup

In this article, we’ll show how to install the gem on a Ruby on Rails project, using the Rspec gem to write our specs. Let’s see an example of how to install and setup the Simplecov:

# On your Gemfile

gem 'simplecov', require: false, group: :test

# On your terminal

$ bundle install

The next step is to set up the Simplecov to run when always when the test suit runs. Here goes an example of how to set it:

# On your spec_helper.rb file

require 'simplecov'

SimpleCov.start :rails

Easy peasy!

Using this setup, you’ll start your reports with separated groups for your Controllers, Models, and Helpers. Next, we will demonstrate how to specialize the report built with more file groups:

# On your spec_helper.rb file

SimpleCov.start :rails do
  add_group 'Models', 'app/models/'
  add_group 'Controllers', 'app/controllers/'
  add_group 'Services', 'app/services/'
  add_filter 'vendor'

Checking the Report

Once configured, Simplecov will automatically measure coverage as your tests are run. When the test process has been completed, the report will be generated and saved on the root of the project by default.

You can see it opening the


file on the coverage directory on your preferred browser.

In a Debian/Ubuntu Terminal you can use this command:

open coverage/index.html. 

In a Mac terminal, you can use this command:

xdg-open coverage/index.html.

The coverage result report is a web page sortable and fully browsable. Using the report, you’ll identify the part of your code that was uncovered, as well as the percentage of coverage for the file and for the project too.

That’s it for today - hope you like this post.