Code coverage

suggest change

Code coverage measures which lines, branches, and methods of your source code are executed when your automated test suite runs. In Ruby, code coverage is measured at the runtime level using Ruby's built-in Coverage standard library module or through the ubiquitous SimpleCov gem.


1. The Built-in Coverage Module

Ruby includes a low-level Coverage module in its standard library. It tracks execution counts directly within the CRuby VM. Only files loaded after Coverage.start are measured, so the code under test must live in a separate file:

# discount.rb
def calculate_discount(price, member)
  if member && price > 50
    price * 0.8
  else
    price
  end
end
require 'coverage'

# Start measurement (specify modes: lines, branches, methods)
Coverage.start(lines: true, branches: true)

# Load the code to measure AFTER starting coverage
require_relative 'discount'

calculate_discount(100, true)

# Retrieve results and stop coverage tracking
result = Coverage.result
puts result.inspect
# {"/path/to/discount.rb" => {lines: [1, 1, 1, nil, 0, nil, nil],
#   branches: {[:if, 0, 2, 2, 6, 5] => {[:then, 1, 3, 4, 3, 15] => 1, [:else, 2, 5, 4, 5, 9] => 0}}}}

The output returns a hash keyed by filename where values indicate the execution count for each source line (nil denotes non-executable lines such as else or end).


2. Using SimpleCov with RSpec or Minitest

While the raw Coverage module provides raw numbers, SimpleCov formats this data into interactive HTML dashboards, groups files logically (e.g. Models, Controllers, Services), and integrates with CI/CD pipelines.

Installation

Add simplecov to your Gemfile:

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

Run bundle install.

Critical Setup Rule: Start Before Loading Application Code

SimpleCov must be required and started at the very first line of your test bootstrap file (spec/spec_helper.rb or test/test_helper.rb). If application classes are required before SimpleCov.start, their definitions will not be tracked.

# spec/spec_helper.rb
require 'simplecov'

SimpleCov.start do
  # Ignore test files, vendor directories, and configuration
  add_filter '/spec/'
  add_filter '/config/'
  add_filter '/vendor/'

  # Group files in the generated report
  add_group 'Models', 'app/models'
  add_group 'Controllers', 'app/controllers'
  add_group 'Services', 'app/services'
end

# Require the rest of your application or test frameworks AFTER SimpleCov.start
require 'rspec'
require_relative '../lib/my_app'

When you run bundle exec rspec, SimpleCov automatically generates an HTML report in coverage/index.html.


3. Branch Coverage

Line coverage only verifies that a line was touched; it does not guarantee that every conditional branch on that line was evaluated. Enabling branch coverage detects untested if/else paths and ternary branches:

SimpleCov.start do
  enable_coverage :branch
  primary_coverage :branch
end

In the HTML report, lines with partial branch coverage will be highlighted in yellow, identifying untested boolean conditions.


4. Enforcing Minimum Coverage Thresholds in CI

You can configure SimpleCov to fail your test suite (non-zero exit code, 2 for minimum coverage, 3 for a coverage drop) if total coverage drops below a given threshold or decreases between commits:

SimpleCov.start do
  # Fail CI if total line coverage is below 90%
  minimum_coverage 90

  # Fail CI if any single file has less than 80% coverage
  minimum_coverage_by_file 80

  # Fail if coverage decreases compared to previous run
  refuse_coverage_drop
end

5. Integrating with CI and Codecov / Coveralls

For CI environments (such as GitHub Actions), you can format coverage data as LCOV, JSON, or Cobertura for upload to services like Codecov or Coveralls:

require 'simplecov'
require 'simplecov-lcov'

SimpleCov::Formatter::LcovFormatter.config do |c|
  c.report_with_single_file = true
  c.single_report_path = 'coverage/lcov.info'
end

SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([
  SimpleCov::Formatter::HTMLFormatter,
  SimpleCov::Formatter::LcovFormatter
])

SimpleCov.start

Best Practices and Caveats

  1. Do Not Confuse 100% Coverage with 100% Tested: Code coverage only verifies that code was executed during a test—not that assertions were made or edge cases were validated.
  2. Track Coverage in Merged Pull Requests: Set up branch coverage checks in your pull request workflow to avoid regressions.
  3. Filter Generated and Third-Party Code: Ensure database migrations, template assets, and vendor libraries are excluded so metrics reflect actual business logic.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents