### Start SimpleCov with Configuration Block Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure SimpleCov directly within the start block. This is the most common method for applying settings. ```ruby SimpleCov.start do some_config_option 'foo' end ``` -------------------------------- ### Start SimpleCov in Test Helper Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Load and launch SimpleCov at the beginning of your test setup file to ensure all code is tracked. ```ruby require 'simplecov' SimpleCov.start # Previous content of test helper now starts here ``` -------------------------------- ### Execute Spawned Script with SimpleCov Integration Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Example of how to execute a script using `PTY.spawn` after requiring the SimpleCov spawn configuration file. ```ruby PTY.spawn('ruby -r./.simplecov_spawn my_script.rb') do # ... ``` -------------------------------- ### Start SimpleCov with Rails Profile (Rails Helper) Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md This snippet is specifically for Rails applications and should be placed at the top of your Rails helper file. ```ruby require 'simplecov' SimpleCov.start 'rails' ``` -------------------------------- ### Clone and Run SimpleCov Development Source: https://github.com/simplecov-ruby/simplecov/blob/main/CONTRIBUTING.md Clone the SimpleCov repository, install dependencies, and run the default rake tasks for development. ```bash git clone https://github.com/simplecov-ruby/simplecov.git cd simplecov bundle bundle exec rake ``` -------------------------------- ### Start SimpleCov with a Profile Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Initiate SimpleCov coverage analysis using a predefined profile like 'rails'. You can also extend the profile with additional configuration options. ```ruby SimpleCov.start 'rails' ``` ```ruby SimpleCov.start 'rails' do # additional config here end ``` -------------------------------- ### Configure SimpleCov with a Configure Block Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use a `configure` block for SimpleCov settings, useful for delaying coverage start or adding configuration later. ```ruby SimpleCov.configure do some_config_option 'foo' end ``` -------------------------------- ### Deprecated Minimum Coverage by File/Group Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Example of how to replace deprecated `minimum_coverage_by_file` and `minimum_coverage_by_group` with the modern `coverage` block syntax. ```ruby coverage :line do minimum_per_file 70 minimum_per_file 100, only: "app/x.rb" end ``` -------------------------------- ### SimpleCov Error Message Example Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md An example of the error message printed to STDERR when SimpleCov fails. ```text SimpleCov failed with exit 1 ``` -------------------------------- ### Enable SimpleCov Coverage on Demand Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Conditionally start SimpleCov coverage using an environment variable. This allows running coverage only when explicitly requested. ```ruby SimpleCov.start if ENV["COVERAGE"] ``` -------------------------------- ### Start SimpleCov with Rails Profile Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md For Rails applications, use the 'rails' profile to automatically group coverage by Controllers, Models, Helpers, and Libraries. ```ruby if ENV['RAILS_ENV'] == 'test' require 'simplecov' SimpleCov.start 'rails' end ``` -------------------------------- ### Centralized Configuration with .simplecov File Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use a `.simplecov` file in the project root for shared configuration when merging results from multiple test suites. Each test helper then requires SimpleCov and starts it. ```ruby # .simplecov — configuration only SimpleCov.load_profile 'rails' SimpleCov.skip 'lib/generators' SimpleCov.group 'Models', 'app/models' ``` ```ruby # spec/spec_helper.rb require 'simplecov' SimpleCov.start ``` ```ruby # features/support/env.rb require 'simplecov' SimpleCov.start ``` -------------------------------- ### Configure SimpleCov Start with Custom Formatters and Command Names Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure SimpleCov.start within your test helper to set a custom command name for parallel tests and apply different formatters based on the environment (e.g., CI vs. local development). ```ruby # spec/spec_helper.rb require 'simplecov' SimpleCov.start 'rails' do # Disambiguates individual test runs command_name "Job #{ENV["TEST_ENV_NUMBER"]}" if ENV["TEST_ENV_NUMBER"] if ENV['CI'] formatter SimpleCov::Formatter::SimpleFormatter else formatter SimpleCov::Formatter::MultiFormatter.new([ SimpleCov::Formatter::SimpleFormatter, SimpleCov::Formatter::HTMLFormatter ]) end cover "{app,lib}/**/*.rb" end ``` -------------------------------- ### Load and Use Custom Profile Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Load a custom profile named 'myprofile' which builds upon the 'rails' profile and excludes 'vendor' directories. This custom profile can then be used to start SimpleCov. ```ruby # lib/simplecov_custom_profile.rb require 'simplecov' SimpleCov.profiles.define 'myprofile' do load_profile 'rails' skip 'vendor' # Don't include vendored stuff end ``` ```ruby # features/support/env.rb require 'simplecov_custom_profile' SimpleCov.start 'myprofile' ``` ```ruby # test/test_helper.rb require 'simplecov_custom_profile' SimpleCov.start 'myprofile' ``` -------------------------------- ### Debug Missing Coverage with SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use this trick to debug missing coverage by checking the load order of your code relative to SimpleCov.start. Ensure SimpleCov is required and started before other code is loaded. ```ruby # my_code.rb class MyCode puts "MyCode is being loaded!" def my_method # ... end end # spec_helper.rb / rails_helper.rb / test_helper.rb / .simplecov — whatever SimpleCov.start puts "SimpleCov started successfully!" ``` -------------------------------- ### Define Custom Filter Class Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Create a custom filter by inheriting from SimpleCov::Filter and implementing the matches? method. This example filters files based on line count. ```ruby class LineFilter < SimpleCov::Filter def matches?(source_file) source_file.lines.count < filter_argument end end SimpleCov.skip LineFilter.new(5) ``` -------------------------------- ### Configure SimpleCov for Forked Subprocesses Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Enable SimpleCov to observe subprocesses started with `Process.fork`. This configuration should be done before `Process.fork` is called. The child process will have its command name appended with subprocess information and its results will merge back into the parent. ```ruby SimpleCov.merge_subprocesses true SimpleCov.at_fork do |pid| # This needs a unique name so it won't be overwritten SimpleCov.command_name "#{SimpleCov.command_name} (subprocess: #{pid})" # be quiet, the parent process will be in charge of output and checking coverage totals SimpleCov.print_errors false SimpleCov.formatter SimpleCov::Formatter::SimpleFormatter SimpleCov.minimum_coverage 0 # start SimpleCov.start end ``` -------------------------------- ### Change SimpleCov Report Location Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Set `SimpleCov.coverage_path` to specify a custom directory for the coverage report, useful for out-of-tree build setups. ```ruby SimpleCov.start do root '/source/checkout' coverage_path '/tmp/build/coverage' end ``` -------------------------------- ### Get Per-File Coverage Stats Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Retrieve coverage statistics for a specific file using the `coverage` command. Use `--json` for raw JSON output or `--input` to specify a coverage file. ```sh simplecov coverage app/models/user.rb ``` ```sh simplecov coverage --json app/models/user.rb ``` ```sh simplecov coverage --input path/to/coverage.json ... ``` -------------------------------- ### Configure SimpleCov to Disable Default Filters Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Call `no_default_skips` to clear all previously defined filters, ensuring that subsequent `skip` directives start with a clean slate. ```ruby SimpleCov.start do no_default_skips end ``` -------------------------------- ### JSON Coverage Report Schema Structure Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md An example of the top-level structure for a coverage.json report, including metadata, aggregate statistics, file-specific coverage, grouped coverage, and error violations. ```json { "$schema": "https://raw.githubusercontent.com/simplecov-ruby/simplecov/main/schemas/coverage-v1.0.schema.json", "meta": { /* schema_version, simplecov_version, command_name, project_name, timestamp, root, commit, line_coverage, branch_coverage, method_coverage */ }, "total": { /* aggregate stats for lines (and branches / methods when enabled) */ }, "coverage": { "": { /* per-file lines, source, branches, methods, etc. */ } }, "groups": { "": { /* per-group stats + files */ } }, "errors": { /* minimum_coverage, minimum_coverage_by_file, minimum_coverage_by_group, maximum_coverage, maximum_coverage_drop violations */ } } ``` -------------------------------- ### Set Test Suite Name with SimpleCov.command_name Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Assign a unique name to each test suite to prevent coverage results from overwriting each other. This is crucial for accurate merging, especially in non-standard setups. ```ruby # test/unit/some_test.rb SimpleCov.command_name 'test:units' ``` ```ruby # test/functionals/some_controller_test.rb SimpleCov.command_name "test:functionals" ``` ```ruby # test/integration/some_integration_test.rb SimpleCov.command_name "test:integration" ``` ```ruby # features/support/env.rb SimpleCov.command_name "features" ``` -------------------------------- ### Define Block Filter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Define a custom filter using a block that receives a SimpleCov::SourceFile object. Return true to exclude the file. This example excludes files with fewer than 5 lines. ```ruby SimpleCov.start do skip do |source_file| source_file.lines.count < 5 end end ``` -------------------------------- ### Define Array Filter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Combine multiple filter types (String, Regexp, Proc, Filter class) into a single array to apply them simultaneously. This example includes all filter types. ```ruby SimpleCov.start do proc = Proc.new { |source_file| false } skip ["string", /regex/, proc, LineFilter.new(5)] end ``` -------------------------------- ### Run Tests with SimpleCov Autostart Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Execute a command with SimpleCov pre-loaded, useful when a `test_helper.rb` hook is not present. This sets the `RUBYOPT` environment variable for the child process. ```sh simplecov run bundle exec rspec ``` ```sh simplecov run -- bundle exec rake test ``` ```sh simplecov run ruby my_test.rb ``` -------------------------------- ### Equivalent Configuration for Strict Profile Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md This configuration block demonstrates the equivalent settings for the 'strict' profile, enabling branch, method, and optionally eval coverage with minimum thresholds set to 100%. ```ruby SimpleCov.start do enable_coverage :branch enable_coverage :method enable_coverage :eval if Coverage.respond_to?(:supported?) && Coverage.supported?(:eval) minimum_coverage line: 100, branch: 100, method: 100 end ``` -------------------------------- ### Configure SimpleCov for Spawned Subprocesses Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Set up SimpleCov to cover Ruby scripts launched with `PTY.spawn`, `Open3.popen`, `Process.spawn`, etc. Create a `.simplecov_spawn.rb` file in the project root and require it using `ruby -r` before executing the script. ```ruby # .simplecov_spawn.rb require 'simplecov' # this will also pick up whatever config is in .simplecov, # so ensure it just contains configuration and doesn't call SimpleCov.start. SimpleCov.command_name 'spawn' # As this isn't for a test runner directly, the script has no pre-defined base command_name SimpleCov.at_fork.call(Process.pid) # Use the per-process setup described above SimpleCov.start # only now can we start ``` -------------------------------- ### Suite-Wide Expected Coverage (Pinning) Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Pin the coverage to an exact percentage by setting both minimum and maximum coverage to the same value. This floors the actual percentage to two decimal places. ```ruby SimpleCov.expected_coverage 95.42 ``` -------------------------------- ### Serve Coverage Report with SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Host the coverage report via HTTP using `simplecov serve`. Specify the port and host to bind to. This is useful for accessing reports on remote machines. ```sh simplecov serve --port N --host HOST ``` -------------------------------- ### Configure File Inclusion and Exclusion Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use the 'cover' and 'skip' directives within SimpleCov.start to define which files are included in the coverage report. 'skip' filters are applied before 'cover' filters. ```ruby SimpleCov.start do cover "{app,lib}/**/*.rb" skip "app/legacy" end ``` -------------------------------- ### Configuring Per-Criterion Coverage Thresholds Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure line, branch, and method coverage thresholds, including minimums, per-file minimums, per-group minimums, and maximum drops. Specific files or groups can have overridden thresholds. ```ruby SimpleCov.start do coverage :line do minimum 90 minimum_per_file 80 minimum_per_file 100, only: "app/mailers/request_mailer.rb" minimum_per_group 95, only: "Models" maximum_drop 5 end coverage :branch, minimum: 80 coverage :method, minimum: 100 end ``` -------------------------------- ### Migrate SimpleCov Minimum Coverage by File Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md The `minimum_coverage_by_file` method is replaced by a `coverage` block. Use `minimum_per_file` within the block to set thresholds, with an optional `only:` argument for specific files. ```ruby SimpleCov.start do minimum_coverage_by_file line: 70, 'app/x.rb' => 100 end ``` ```ruby SimpleCov.start do coverage(:line) { minimum_per_file 70; minimum_per_file 100, only: 'app/x.rb' } end ``` -------------------------------- ### Compare Coverage Deltas with SimpleCov Diff Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Analyze coverage changes between a baseline and current reports using `simplecov diff `. It shows line, branch, and method deltas for files. Use `--fail-on-drop` to exit non-zero on coverage decrease and `--threshold` to filter small deltas. Output can be JSON using `--json`. ```sh $ simplecov diff coverage/baseline.json -20.00% lines -10.00% branches lib/foo.rb + 5.00% lines lib/bar.rb +60.00% lines lib/new.rb (new file) -95.00% lines lib/gone.rb (removed) ``` ```sh $ simplecov diff --json coverage/baseline.json [ {"file":"lib/foo.rb","status":"changed","line_delta":-20.0,"branch_delta":-10.0,"method_delta":0.0}, {"file":"lib/bar.rb","status":"changed","line_delta":5.0,"branch_delta":0.0,"method_delta":0.0} ] ``` -------------------------------- ### Configure SimpleCov Positive File Scope Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use the `cover` method with glob patterns to define a positive scope (allowlist) for files to be included in coverage reports. Multiple `cover` calls will union their patterns. ```ruby SimpleCov.start do cover "lib/**/*.rb" end ``` -------------------------------- ### Generate Stripped Down Rails App Source: https://github.com/simplecov-ruby/simplecov/blob/main/test_projects/rails/README.md Use this command to create a minimal Rails application for testing SimpleCov interactions. It skips several components to reduce complexity. ```bash rails new --skip-action-mailer --skip-action-mailbox --skip-action-text --skip-active-storage --skip-action-cable --skip-javascript --skip-turbolinks --skip-sprockets --skip-git --skip-keep --skip-listen some_name ``` -------------------------------- ### Migrate SimpleCov Filters and Groups Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use `skip` instead of `add_filter` for excluding files and `group` instead of `add_group` for organizing code. These changes maintain identical matcher grammar and behavior. ```ruby SimpleCov.start do add_filter "/test/" add_filter %r{\Aconfig/} add_group "Models", "app/models" end ``` ```ruby SimpleCov.start do skip "/test/" skip %r{\Aconfig/} group "Models", "app/models" end ``` -------------------------------- ### List Lowest Coverage Files with SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use `simplecov uncovered` to display files with the lowest line coverage. Options include filtering by threshold, limiting the number of results, and changing the coverage criterion (line, branch, method). Use `--json` to output results as a JSON array. ```sh $ simplecov uncovered 50.00% 5/10 lib/foo.rb 80.00% 8/10 lib/bar.rb $ simplecov uncovered --threshold 90 --top 5 $ simplecov uncovered --criterion branch ``` -------------------------------- ### Set SimpleCov Configuration Directly Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Apply SimpleCov configuration options as direct setters. This offers an alternative to using a configuration block. ```ruby SimpleCov.some_config_option 'foo' ``` -------------------------------- ### Open HTML Coverage Report Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use the SimpleCov CLI to open the generated HTML coverage report in your default browser. ```sh simplecov open ``` -------------------------------- ### Configure SimpleCov to Opt Out of Formatting Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md To disable all formatting and only generate the `.resultset.json` file for collation in parallel test runs, use `formatter false` or `formatters []`. ```ruby SimpleCov.start do formatter false end ``` ```ruby SimpleCov.start do formatters [] end ``` -------------------------------- ### Register a Custom Parallel Test Runner Adapter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Define and register a custom adapter for a parallel test runner that uses different environment variables or synchronization APIs. This custom adapter will be tried before the built-in adapters. ```ruby # In your spec_helper.rb / test_helper.rb (before SimpleCov.start) class MyRunnerAdapter < SimpleCov::ParallelAdapters::Base def self.active? !ENV["MY_RUNNER_PID"].nil? end def self.first_worker? ENV["MY_RUNNER_PID"].to_i == 1 end def self.wait_for_siblings MyRunner.barrier! # if your runner provides a sync primitive end def self.expected_worker_count ENV["MY_RUNNER_WORKERS"].to_i end end SimpleCov::ParallelAdapters.register MyRunnerAdapter ``` -------------------------------- ### Migrate SimpleCov Merging and Subprocess Options Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md The `use_merging` option is replaced by `merging`, and `enable_for_subprocesses` is replaced by `merge_subprocesses`. Both retain their original boolean functionality. ```ruby SimpleCov.start do use_merging true enable_for_subprocesses true end ``` ```ruby SimpleCov.start do merging true merge_subprocesses true end ``` -------------------------------- ### Eager Load Rails Application with SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md When using Spring with SimpleCov, explicitly call `Rails.application.eager_load!` after `SimpleCov.start` in your `test_helper.rb` or `spec_helper.rb` to resolve eager-loading issues. ```ruby require 'simplecov' SimpleCov.start 'rails' Rails.application.eager_load! ``` -------------------------------- ### Clean Coverage Reports with SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Remove the coverage report directory using `simplecov clean`. Use `--dry-run` to preview deletions or `-q`/`--quiet` to suppress status messages. ```sh simplecov clean ``` -------------------------------- ### Migrate SimpleCov File Tracking and Coverage Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Replace `track_files` with `cover` for specifying files to be included in coverage reports. `cover` also restricts the report to matching files, unlike `track_files`. For enabling eval coverage, use `enable_coverage :eval`. ```ruby SimpleCov.start do track_files "lib/**/*.rb" enable_coverage_for_eval end ``` ```ruby SimpleCov.start do cover "lib/**/*.rb" enable_coverage :eval end ``` -------------------------------- ### Enable Oneshot Line Coverage in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Enable oneshot line coverage as a faster alternative to traditional line coverage. It records only the first execution of each line, reducing overhead. ```ruby SimpleCov.start do enable_coverage :oneshot_line primary_coverage :oneshot_line end ``` -------------------------------- ### Use HTML Formatter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure SimpleCov to use the built-in HTML formatter for generating reports. ```ruby SimpleCov.formatter = SimpleCov::Formatter::HTMLFormatter ``` -------------------------------- ### Cover Files Outside Project Root Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Adjust SimpleCov.root to a broader directory and use 'skip' filters to include files outside the default project root, such as those in sibling directories or engines. ```ruby SimpleCov.root '/' SimpleCov.start :rails do skip { |src| !src.filename.start_with?(Rails.root.to_s, '/path/to/my_engine') } end ``` -------------------------------- ### Migrate SimpleCov Minimum Coverage by Group Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Similar to file-specific coverage, group coverage thresholds are now set within a `coverage` block using `minimum_per_group`, with an `only:` option to target specific groups. ```ruby SimpleCov.start do minimum_coverage_by_group 'Models' => { line: 90 } end ``` ```ruby SimpleCov.start do coverage(:line) { minimum_per_group 90, only: 'Models' } end ``` -------------------------------- ### Access Coverage Data in Ruby Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Obtain coverage results and query specific file coverage statistics programmatically within a Ruby script. ```ruby result = SimpleCov.result result.coverage_for("app/models/user.rb") # => {line: , branch: , method: } ``` ```ruby result.source_file_for("app/models/user.rb") # => ``` -------------------------------- ### Run Coverage with Environment Variable Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Execute tests with coverage enabled by setting the COVERAGE environment variable. ```sh COVERAGE=true rake test ``` -------------------------------- ### Use JSON Formatter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure SimpleCov to use the built-in JSON formatter for generating coverage reports in JSON format. ```ruby SimpleCov.formatter = SimpleCov::Formatter::JSONFormatter ``` -------------------------------- ### Generate Terminal Coverage Report Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Display overall and per-group coverage totals directly in the terminal. Use `--input` to specify a non-default coverage file or `--json` to output totals as a JSON object. ```sh simplecov report ``` ```sh simplecov report --input PATH ``` ```sh simplecov report --json ``` -------------------------------- ### Add SimpleCov to Gemfile Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Include SimpleCov as a development dependency in your Gemfile for testing purposes. ```ruby gem 'simplecov', require: false, group: :test ``` -------------------------------- ### Suite-Wide Per-Criterion Minimum Coverage Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Set specific minimum coverage percentages for different criteria like line and branch. ```ruby SimpleCov.minimum_coverage line: 90, branch: 80 ``` -------------------------------- ### Merge Coverage Resultsets with SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Combine `.resultset.json` files from parallel CI workers using `simplecov merge`. Specify input files and an output path. Options include honoring merge timeouts, performing a dry run, and suppressing output with `--quiet`. ```sh $ simplecov merge worker-*/coverage/.resultset.json --output coverage/.resultset.json ``` -------------------------------- ### Define and Publish Profile Gem Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Define a custom profile named 'myteam' within a gem. This profile enables branch coverage, specifies files to cover, and skips a particular directory. Gems defining profiles can be automatically loaded by SimpleCov. ```ruby # In a gem named simplecov-profile-myteam SimpleCov.profiles.define "myteam" do enable_coverage :branch cover "{app,lib}/**/*.rb" skip "app/legacy" end ``` -------------------------------- ### Suite-Wide Minimum Coverage Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Set a suite-wide minimum coverage percentage for the primary criterion (defaults to line coverage). ```ruby SimpleCov.minimum_coverage 90 ``` -------------------------------- ### Suite-Wide Maximum Coverage Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Set a suite-wide maximum coverage percentage for a specific criterion. ```ruby SimpleCov.maximum_coverage line: 90 ``` -------------------------------- ### Define File Groups in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure SimpleCov to group source files into categories like Models, Controllers, or based on custom logic such as file line count or multiple paths. This helps in organizing coverage reports. ```ruby SimpleCov.start do group "Models", "app/models" group "Controllers", "app/controllers" group "Long files" do |src_file| src_file.lines.count > 100 end group "Multiple Files", ["app/models", "app/controllers"] # You can also pass in an array group "Short files", LineFilter.new(5) # Using the LineFilter class defined in the Filters section above end ``` -------------------------------- ### Use Multiple Formatters Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure SimpleCov to use multiple formatters, such as HTML and Cobertura, for generating different report formats. Ensure to require any additional formatter gems. ```ruby require "simplecov-cobertura" SimpleCov.formatters = [ SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::CoberturaFormatter, ] ``` -------------------------------- ### Ignore Coverage Results in Git Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Add the 'coverage' directory to your .gitignore file to prevent coverage reports from being committed to version control. ```sh echo coverage >> .gitignore ``` -------------------------------- ### Run Individual RSpec Tests Source: https://github.com/simplecov-ruby/simplecov/blob/main/CONTRIBUTING.md Execute specific RSpec test files within the SimpleCov project. ```bash bundle exec rspec path/to/test.rb ``` -------------------------------- ### Disable Spring for SimpleCov Tests Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md An alternative to configuring eager loading is to disable Spring by setting the `DISABLE_SPRING` environment variable to `1` when running Rake tasks. ```shell DISABLE_SPRING=1 rake test ``` -------------------------------- ### Ensure Unique Command Names for Parallel Tests Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md When running tests in parallel, ensure each process has a unique command name to avoid data loss. Incorporate environment variables like TEST_ENV_NUMBER for proper merging with tools like parallel_tests. ```ruby # spec/spec_helper.rb SimpleCov.command_name "features" + (ENV['TEST_ENV_NUMBER'] || '') ``` -------------------------------- ### Apply Dark/Light Mode Preference Source: https://github.com/simplecov-ruby/simplecov/blob/main/lib/simplecov/formatter/html_formatter/public/index.html Applies a saved dark or light mode preference from localStorage to the document's root element. This prevents a visual flash of the default theme before the preference is applied. It handles cases where localStorage might be unavailable. ```javascript try { const pref = localStorage.getItem('simplecov-dark-mode'); if (pref === 'dark' || pref === 'light') { document.documentElement.classList.add(`${pref}-mode`); } } catch (_error) { // localStorage can be unavailable in locked-down browser contexts. } ``` -------------------------------- ### Configure SimpleCov Collate with Custom Formatters Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md When collating results across environments, you can specify a profile and a configuration block to apply specific formatters to the final merged report, such as using SimpleCov::Formatter::MultiFormatter. ```ruby # lib/tasks/coverage_report.rake namespace :coverage do task :report do require 'simplecov' SimpleCov.collate Dir["simplecov-resultset-*/.resultset.json"], 'rails' do formatter SimpleCov::Formatter::MultiFormatter.new([ SimpleCov::Formatter::SimpleFormatter, SimpleCov::Formatter::HTMLFormatter ]) end end end ``` -------------------------------- ### Configure SimpleCov for Parallel Tests Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use `parallel_tests true` or `parallel_tests false` to explicitly control the auto-requiring of the `parallel_tests` gem. The default behavior auto-detects based on environment variables. ```ruby SimpleCov.start do parallel_tests true end ``` -------------------------------- ### Run Individual Cucumber Tests Source: https://github.com/simplecov-ruby/simplecov/blob/main/CONTRIBUTING.md Execute specific Cucumber feature files within the SimpleCov project. ```bash bundle exec cucumber path/to/test.feature ``` -------------------------------- ### Enable Strict Coverage Profile Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use the bundled 'strict' profile to enforce 100% minimum coverage for lines, branches, and methods. It adapts to different Ruby environments by conditionally enabling coverage criteria. ```ruby SimpleCov.start 'strict' ``` -------------------------------- ### Enable Branch Coverage in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Enable branch coverage to track execution of conditional branches. This is useful for one-line conditionals and guard clauses. ```ruby SimpleCov.start do enable_coverage :branch end ``` -------------------------------- ### Enable Eval Coverage in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Enable eval coverage to measure coverage for code evaluated by `Kernel#eval`. This is typically useful for ERB templates. Ensure `ERB#filename=` is set for accurate source tracing. ```ruby SimpleCov.start do enable_coverage :eval end ``` -------------------------------- ### Suite-Wide Maximum Coverage Drop Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure the maximum allowed drop in coverage percentage between test runs for specified criteria. ```ruby SimpleCov.maximum_coverage_drop line: 5, branch: 10 ``` -------------------------------- ### Default SimpleCov Exit Behavior Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md This snippet shows the default `at_exit` hook in SimpleCov, which formats the coverage results upon test suite completion. ```ruby SimpleCov.at_exit do SimpleCov.result.format! end ``` -------------------------------- ### Define Custom Profile in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Define a custom profile named 'rails' to streamline repetitive configuration. This profile includes skipping certain directories and grouping common Rails application components. ```ruby SimpleCov.profiles.define 'rails' do skip '/test/' skip '/config/' group 'Controllers', 'app/controllers' group 'Models', 'app/models' group 'Helpers', 'app/helpers' group 'Libraries', 'lib' end ``` -------------------------------- ### Ignore Implicit Else Branches in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Enable branch coverage and ignore implicit else branches. This prevents synthetic branches from constructs like `case/when` without `else` or `||=` from negatively impacting the branch coverage percentage. ```ruby SimpleCov.start do enable_coverage :branch ignore_branches :implicit_else end ``` -------------------------------- ### Control SimpleCov Color Output Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Programmatically enable or disable colorized output in SimpleCov diagnostics. Setting to `true` or `false` overrides environment variables and TTY detection. ```ruby SimpleCov.color true ``` ```ruby SimpleCov.color false ``` ```ruby SimpleCov.color :auto ``` -------------------------------- ### Collate Coverage Results Across Execution Environments Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use SimpleCov.collate to merge coverage data from multiple build machines or separate test runs. This is typically done in a Rake task after downloading individual .resultset.json files. ```ruby # lib/tasks/coverage_report.rake namespace :coverage do desc "Collates all result sets generated by the different test runners" task :report do require 'simplecov' SimpleCov.collate Dir["simplecov-resultset-*/.resultset.json"] end end ``` -------------------------------- ### Disable Coverage for Code Sections Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use # simplecov:disable and # simplecov:enable comments to exclude specific lines, branches, or methods from coverage reports. Categories can be combined or omitted to target all three. ```ruby # simplecov:disable line def skipped_lines never_reached end # simplecov:enable line # simplecov:disable branch, method legacy adapter, scheduled for removal class LegacyAdapter def call(value) value ? :yes : :no end end # simplecov:enable raise "absurd" # simplecov:disable ``` -------------------------------- ### Refuse Coverage Drop Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Prevent any drop in coverage between runs by setting the maximum allowed drop to 0 for specified criteria. ```ruby SimpleCov.refuse_coverage_drop :line, :branch ``` -------------------------------- ### Define Regex Filter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use a regular expression filter to exclude files whose paths match the given pattern. This provides more precise control over file exclusion. ```ruby SimpleCov.start do skip %r{^/test/} end ``` -------------------------------- ### Set Primary Coverage Type Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Change the primary coverage type to 'branch' for reporting and exit behavior. Coverage must be enabled for non-default types first. ```ruby SimpleCov.start do enable_coverage :branch primary_coverage :branch end ``` ```ruby SimpleCov.primary_coverage :branch ``` -------------------------------- ### Define String Filter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use a string filter to exclude files whose paths contain the specified string. This is useful for excluding test directories. ```ruby SimpleCov.start do skip "/test/" end ``` -------------------------------- ### Disable Source in JSON Coverage Report Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Configure the JSON formatter to exclude the source code text from the coverage report payload. This reduces file size, and source can be retrieved from repository history if needed. ```ruby SimpleCov.start do source_in_json false end ``` -------------------------------- ### Disable Line Coverage in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Enable branch coverage and disable line coverage for a branch-only report. Ensure at least one coverage criterion remains enabled. ```ruby SimpleCov.start do enable_coverage :branch disable_coverage :line end ``` -------------------------------- ### Remove Default Filter Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Remove a specific default filter, such as the hidden file filter, to include files in dot directories. ```ruby SimpleCov.start do remove_filter(/\A\..*/) end ``` -------------------------------- ### Ignore Eval-Generated Branches and Methods in SimpleCov Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Enable branch and method coverage while ignoring eval-generated entries. This is useful for code generated by macros like Rails' `delegate` to avoid synthetic branches or methods in coverage reports. ```ruby SimpleCov.start do enable_coverage :branch enable_coverage :method ignore_branches :eval_generated ignore_methods :eval_generated end ``` -------------------------------- ### Disable SimpleCov Error Messages Source: https://github.com/simplecov-ruby/simplecov/blob/main/README.md Use this to suppress error messages printed to STDERR when SimpleCov encounters an issue. ```ruby SimpleCov.print_errors false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.