Simplecov is a Ruby code coverage tool. This article documents the integration with a Rails 8 application, with the minitest test framework.
Setup
-
Include the simplecov gem in Gemfile.
gem "rails", "~> 8.1" gem "minitest", "~> 5" gem "simplecov", require: false -
Install the gem.
bundle install
Integrate
-
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 -
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 -
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
-
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 -
The result can be located in the
coveragedirectory.