
Oct 29, 2025
SimpleCov Setup for Rails Projects

Dariusz Michalski
CEO
Learn how to set up SimpleCov in Rails projects for enhanced test coverage and quality assurance with practical guidelines and best practices.
Want to boost your Rails app's test coverage? SimpleCov makes it easy.
SimpleCov tracks which parts of your code are tested and generates detailed reports showing what's covered and what's not. This helps you identify gaps in your test suite, ensuring your application is reliable and well-tested. Here's a quick guide to getting started:
Why SimpleCov? It integrates with RSpec or Minitest to provide clear, colour-coded reports (green for tested lines, red for untested ones).
Swiss Teams' Standards: Swiss developers often aim for 80–90% test coverage, especially in critical sectors like finance or healthcare.
Setup Requirements: Use Ruby 2.5+ and a testing framework (RSpec or Minitest). Add SimpleCov to your Gemfile, then configure it in your test helper file.
Key Features: SimpleCov's Rails profile organises reports into categories (Controllers, Models, etc.) and allows custom filters and thresholds.
Whether you're improving a legacy app or starting fresh, SimpleCov ensures your code is tested and ready for production.
Prerequisites and Setup Requirements
Requirements for Using SimpleCov

Before diving into SimpleCov, you'll need a functional Rails application since SimpleCov analyses an existing codebase.
Make sure you're running Ruby 2.5 or later, including any Ruby 3.x version. To confirm your Ruby version, run ruby -v in your terminal.
You'll also need a testing framework, as SimpleCov tracks code execution during test runs. Both RSpec and Minitest are compatible, though their setup processes differ slightly. For RSpec, you'll configure SimpleCov in the spec_helper.rb file, while Minitest users will make changes in test_helper.rb.
Bundler is another requirement. Since SimpleCov is distributed as a Ruby gem, Bundler will help you manage this dependency.
One critical point: SimpleCov has to be loaded before any application code to accurately track coverage. Place the SimpleCov configuration at the top of your test helper file, ahead of other require statements or Rails environment loading.
Environment and Local Development Setup
Swiss development teams often follow local conventions when setting up SimpleCov to ensure consistency across projects.
By default, SimpleCov generates reports in the /coverage directory. Make sure this directory fits within your project’s structure and doesn’t overlap with existing folders.
Keep your file paths and naming conventions consistent with the rest of your Rails application. If your project follows specific patterns for test files or configurations, stick to those when integrating SimpleCov.
For date and time formatting in coverage reports, SimpleCov uses your system’s locale settings. Swiss developers working with international teams should note that timestamps may appear in different formats. To avoid confusion, consider standardising reports to the DD.MM.YYYY date format and a 24-hour clock.
Coverage percentages in SimpleCov follow standard decimal notation, such as 87.5%. This aligns well with Swiss formatting, where commas are used for thousands and dots for decimals.
Lastly, don’t forget to add /coverage to your .gitignore file. These reports can be large and change frequently, making them unsuitable for version control.
Once you’ve set up SimpleCov locally, you can move on to configuring it for containerised environments and automated pipelines.
Docker and CI/CD Setup

If your Rails app runs in Docker, there are a few extra steps to ensure SimpleCov works smoothly. After adding SimpleCov to your Gemfile, rebuild your Docker image. Limit SimpleCov to test environment containers to avoid adding unnecessary dependencies to production.
To access the HTML reports generated by SimpleCov, configure your Docker setup to map the /coverage directory to the host. Without this mapping, the reports will remain inside the container and be inaccessible.
For CI/CD pipelines, platforms like GitHub Actions and GitLab CI can automatically run your test suite and generate coverage reports. Configure your pipeline to execute tests in the correct environment and collect coverage data during the build process.
Swiss teams often integrate coverage reporting into their CI/CD workflows. For example, you can set up your pipeline to comment on pull requests with coverage changes. This approach supports thorough code reviews and helps maintain high-quality standards. You can also configure the pipeline to flag any drop in coverage below a certain threshold, preventing potential regressions.
In CI/CD environments, you might need to use environment variables to adjust SimpleCov’s behaviour. Ensure the test environment in your automated setup mirrors your local configuration and that all required gems are available. This consistency will help avoid issues during automated testing.
Installing and Configuring SimpleCov
Installing the SimpleCov Gem
To get started with SimpleCov, you need to add it to your Gemfile. Locate the :test group in the file and include SimpleCov with the require parameter:
The require: false parameter is crucial because SimpleCov needs to be manually loaded at the very top of your test helper file. If this parameter is omitted, Bundler will automatically load SimpleCov when your application starts, which can result in missing coverage data for any code executed before your test suite begins.
After updating your Gemfile, run the following command in your terminal to install SimpleCov and its dependencies:
SimpleCov supports Ruby versions 2.5 and above. Once installed, you’re ready to configure it to track test coverage from the beginning of your test suite.
Basic SimpleCov Configuration
To configure SimpleCov, you must include it at the very start of your test helper file - before any other require statements or Rails environment setup.
Here’s how to set it up for different testing frameworks:
RSpec projects: Add this to the very top of
spec_helper.rb:Minitest projects: Place the same configuration at the top of
test/test_helper.rb:Cucumber: Include this at the start of
features/support/env.rb:
Order matters here. SimpleCov integrates with Ruby's Coverage library to monitor which lines of code are executed during tests. If you call SimpleCov.start after your application code has already loaded, SimpleCov won’t capture coverage data for that code, leading to incomplete reports.
This is especially important when using Spring, Rails' preloader that keeps your application loaded between test runs. Even with Spring active, ensure SimpleCov is initialised before the preloader kicks in.
Using the Rails Profile
For Rails projects, you can streamline your setup by using the Rails-specific profile. Instead of the generic SimpleCov.start, use:
The Rails profile organises coverage data into categories that align with Rails' structure. Instead of a flat list of files, your report will be neatly divided into sections like Controllers, Models, Helpers, and Libraries, making it easier to spot areas that need more test coverage.
Additionally, the Rails profile automatically excludes files and directories that shouldn’t affect your coverage metrics, such as test files and configuration directories. This saves you from manually configuring these exclusions and aligns with Rails conventions by default.
You can also customise the Rails profile to better suit your project’s structure. For example:
add_group: Creates custom categories for directories likeapp/services/.add_filter: Excludes specific directories from coverage reports, such asvendororconfig.
This flexibility is particularly useful for teams that need to tailor coverage reports to match their project’s organisation or compliance standards.
Viewing Your Coverage Reports
After running your test suite, SimpleCov generates detailed HTML reports in a coverage/ directory at the root of your project. These reports include colour-coded indicators - green for covered lines and red for uncovered ones - making it easy to assess your test coverage at a glance.
Checking Code coverage in Rails with simplecov
Customising SimpleCov for Rails Projects
After setting up SimpleCov with a basic Rails configuration, you can tailor it further to meet the specific needs of your project and ensure it aligns with high-quality standards. While the default setup works for most Rails applications, tweaking filters, thresholds, and report formats allows for more precise control over what gets measured and how the data is reviewed.
Excluding Files and Directories
Not every file in your Rails project needs to be included in coverage tracking. For example, view templates, configuration files, and third-party libraries can distort your metrics and distract from the code that truly matters. SimpleCov’s add_filter method makes it easy to exclude files and directories from coverage calculations.
Here’s an example of how to exclude common directories that don’t influence your coverage metrics:
app/views: View templates often contain mostly HTML with embedded Ruby, which is typically tested indirectly through integration tests.node_modulesandvendor: These directories contain third-party code and are not part of your application logic.
For more specific exclusions, you can use pattern matching:
This approach is particularly useful for larger Rails projects, where certain directories or file types might not need coverage tracking.
Setting Coverage Thresholds
Coverage thresholds help maintain consistent code quality by failing the test suite if coverage falls below a defined percentage. This is especially useful for teams working on distributed projects, ensuring everyone adheres to the same standards.
To set a minimum coverage threshold, use the minimum_coverage method:
Starting with a threshold of 70–80% is a good idea, especially for legacy projects with lower initial coverage. You can gradually increase this as the codebase improves. Be cautious with overly strict thresholds, as they can slow down development, particularly when working with older code.
For more granular control, set different thresholds for line and branch coverage:
Line coverage tracks which lines of code were executed during tests.
Branch coverage ensures all possible code paths (e.g.,
if/elsestatements) are tested. Since branch coverage is harder to achieve, starting with a lower threshold is practical.
Integrating these thresholds into your CI/CD pipelines ensures that code with insufficient test coverage doesn’t get merged, maintaining high-quality standards across the team.
Output Formats and Report Locations
By default, SimpleCov generates HTML reports, but you can customise the output to include other formats like JSON or LCOV, depending on your needs. For example, LCOV reports are ideal for CI tools and code quality platforms.
To change the report directory, use coverage_dir:
Saving reports in public/coverage makes them accessible to team members and stakeholders via your web server. This can be particularly helpful for teams needing to share coverage data with clients or auditors.
To output multiple formats, install additional formatter gems:
The LCOV format is especially useful for integrating with CI tools that require standardised formats.
Here’s an example of a more comprehensive configuration:
This setup excludes unnecessary files, enforces an 85% coverage threshold, outputs reports in LCOV format to a public directory, and organises coverage data into custom groups for better clarity.
Reading and Using Coverage Reports
Once SimpleCov generates your coverage report, the real work begins. The HTML report, located at coverage/index.html, is packed with details about your Rails application's test coverage. Learning how to interpret this data is crucial for improving your code quality.
Understanding the Coverage Report
When you open the SimpleCov report, you’ll first see a summary dashboard. At the top, it highlights your overall coverage percentage - your quick snapshot of how well your test suite is performing. Below that, the report breaks down coverage by file and directory, showing individual percentages for each.
The colour-coding system is a handy visual aid. It helps you quickly spot areas that need attention. Clicking on a specific file brings up a line-by-line breakdown of your code, with colour indicators showing coverage status. Each line is displayed alongside the actual code, making it easy to identify untested methods, conditionals, or error-handling paths. The Rails profile further organises data into categories like Controllers, Models, Helpers, and Services, offering insights into how well different parts of your application are tested.
The report also provides key metrics, such as the total number of lines in your codebase, the number covered by tests, and the resulting percentage. For example, if your report shows 1'800 out of 2'000 lines covered, your coverage is 90.0%. Additionally, it breaks these figures down by file type and directory, helping you see if your models are better tested than your controllers or if specific areas need more attention. These insights help you pinpoint gaps in your test suite.
Finding Untested Code
To identify gaps, start by reviewing files with the lowest coverage percentages. Pay attention to red-highlighted lines, which indicate completely untested code, but don’t overlook yellow-highlighted lines that show partial coverage.
Partial coverage often signals missed edge cases or untested error-handling scenarios. For instance, a controller action might be partially covered because your tests only handle the "happy path", ignoring validation failures or exceptions. These scenarios are critical for ensuring your application’s stability and user experience.
Focus on addressing critical business logic first. For example, a payment processing method with only 60% coverage should take priority over a rarely used utility function. Pay special attention to Models and Services, as they often house essential logic.
The file-by-file view helps you trace execution paths in your code. If you spot a red line in the middle of a method, think about the conditions that would trigger that line. This often reveals the need for additional test cases to cover different inputs, user permissions, or system states.
When reviewing controllers, consider all HTTP methods and response formats. For example, your create action might have good coverage for successful cases but lack tests for validation errors or unauthorised access. Similarly, API endpoints might cover JSON responses but skip over XML or other formats.
Upholding Coverage Thresholds
Setting coverage thresholds in your SimpleCov configuration ensures consistent quality. Many Swiss development teams aim for a minimum of 90% coverage for critical systems, reflecting the country’s focus on precision and high standards. These thresholds should be tailored to your project's risk level and any regulatory requirements.
By integrating these thresholds into your CI/CD pipelines, you can automatically enforce them. Configure your system to fail builds if coverage drops below the required level. This prevents untested code from being merged into the main branch and ensures quality is maintained throughout the development process.
Regularly reviewing coverage reports is another effective strategy. Schedule weekly or bi-weekly sessions where the team examines coverage trends and identifies areas for improvement. Use the report's grouping features to assign responsibilities for specific parts of the application and track progress.
Transparency and documentation also help maintain high standards. Adding coverage badges to your project’s README file makes the current status visible to all stakeholders, including project managers and clients who value quality metrics.
For teams working on legacy Rails applications, it’s better to aim for gradual improvement rather than trying to achieve high coverage all at once. Start with realistic thresholds, such as 70-80%, and increase them as you add tests to existing code. Focus on thoroughly testing new features while gradually improving coverage for older components during refactoring or bug fixes.
Finally, incorporate coverage checks into your code review process. When reviewing pull requests, ensure new code includes appropriate tests and that changes to existing code maintain or improve coverage levels. This practice helps embed test coverage as a natural part of development.
Rather than fixating on absolute percentages, use the SimpleCov report to track trends over time. A project that maintains steady 85% coverage while introducing new features demonstrates better testing discipline than one that starts at 95% but declines with each release. Historical data can reveal patterns and help you refine your testing strategies.
Conclusion
Integrating SimpleCov into your development workflow is a straightforward way to elevate your code quality. Getting started is easy: include the gem in your Gemfile's test group, require it in your test helper file, and tweak the configuration to suit your needs. Once set up, SimpleCov generates detailed HTML reports that highlight untested areas in your code, helping your team focus on what needs attention most. This small investment of time can make a big difference in your testing approach.
For Swiss development teams, SimpleCov aligns perfectly with the country's reputation for precision and high standards. By setting a 90% coverage threshold in CI/CD pipelines, teams can ensure that only well-tested code makes it to production. This automated safeguard not only reduces the risk of bugs in critical applications but also upholds the meticulous quality standards Swiss businesses are known for.
Comprehensive test coverage also brings long-term benefits: fewer issues in production, easier maintenance, and greater transparency through visible quality metrics. With a well-tested codebase, developers can confidently refactor and innovate, knowing that any breaking changes will be caught early.
Swiss companies can further enhance their use of SimpleCov by leveraging USEO's expertise in Ruby on Rails development. USEO helps teams implement robust test coverage practices, ensuring software meets both local and international quality standards.
Whether you're improving a legacy application or starting a new project, SimpleCov's adaptability makes it a valuable tool for maintaining high-quality code.
FAQs
How can I set up SimpleCov to work with Docker and CI/CD pipelines in a Rails project?
SimpleCov can be seamlessly integrated into a Ruby on Rails project that uses Docker and CI/CD pipelines, helping to maintain consistent test coverage reporting across different environments. To get started, add SimpleCov to your Gemfile and set it up in your test configuration file (like spec_helper.rb or test_helper.rb). When working with Docker, make sure the configuration accounts for the containerised environment by properly mounting necessary volumes and mapping the directory where the coverage reports are generated.
For CI/CD pipelines, adjust your pipeline script to run tests with SimpleCov enabled. Once the tests finish, ensure the coverage report is collected and, if necessary, uploaded to a central system for easy access. This approach ensures that test coverage remains transparent and accessible, supporting high coding standards throughout the development process.
How can I set up and manage coverage thresholds effectively in SimpleCov for a Rails project?
To configure and manage coverage thresholds with SimpleCov, start by setting the minimum coverage percentages in your configuration file (typically simplecov.rb). Use the SimpleCov.minimum_coverage method to define the overall coverage requirement for your project. Additionally, the SimpleCov.minimum_coverage_by_file method allows you to enforce specific coverage levels for individual files, ensuring consistent quality throughout your codebase.
Keep a close eye on your test coverage reports to verify that these thresholds are being met. If coverage dips below the set levels, it's crucial to address the gaps by writing extra tests. This proactive approach helps maintain a high standard of code quality and reduces the risk of issues making their way into production.
How can I customise SimpleCov to suit the structure and requirements of my Rails application?
To adjust SimpleCov for your Rails application, you can tweak its configuration to fit your project's structure and testing requirements. Start by editing the SimpleCov.start block in your test_helper.rb or spec_helper.rb file. Within this block, you can define which files or folders to include or exclude using options like add_filter and track_files. For example, you might exclude files in config/initializers or focus on specific directories such as app/models.
You can also make your coverage reports easier to read by grouping files into categories with the add_group method. For instance, you could create groups like "Controllers", "Models", and "Helpers" to organise your results. This setup allows you to pinpoint areas that need improvement while providing a clearer snapshot of your test coverage.
Customising SimpleCov ensures your coverage reports are not only detailed but also aligned with your project's specific goals.


