Simplecov is a Ruby code coverage tool. This article documents the integration with a Rails 8 application, with the minitest test framework.


Setup

1) Include the simplecov gem in Gemfile.

gem "rails", "~> 8.1"
gem "minitest", "~> 5"
gem "simplecov", require: false

2) Install the gem.

bundle install

Integrate

1) Edit test/test_helper.rb and these codes at the top of the file.

# frozen_string_literal: true

require "simplecov"
SimpleCov.start "rails" do
  enable_coverage :branch
  command_name "#{ENV['TEST_SUITE'] || 'unit'}-#{Process.pid}"
  merge_timeout 3600
end

2) Optionally, you can add filters to exclude certain files. For example, any files with fewer than 5 lines of code are likely scaffolds.

  add_filter do |source_file|
    source_file.lines.count < 5
  end

3) While simplecov already supports default grouping (such as controllers, mailers, models, jobs), you can create new groups as needed. For example, you have a few classes that fall under the providers group, you can do so:

add_group "Providers", "app/providers"

Execute

1) To combine the full coverage, you can run all the tests together. In the example below, we run both unit testing and system testing.

bin/rails db:test:prepare && \
  TEST_SUITE=unit bin/rails test && \
  TEST_SUITE=system bin/rails test:system

2) The result can be located in the `coverage` directory.