Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Last active December 11, 2021 22:31
Show Gist options
  • Save ndbroadbent/8283815e74455f1cfdc0fd27bbb6e14c to your computer and use it in GitHub Desktop.
Save ndbroadbent/8283815e74455f1cfdc0fd27bbb6e14c to your computer and use it in GitHub Desktop.
How to get accurate SimpleCov coverage with Spring in a Rails application
# Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
if defined?(Spring) && defined?(SimpleCov) && Coverage.running?
SimpleCov.spring_preload_result = Coverage.peek_result
end
group :development, :test do
gem 'spring-commands-rspec', require: false
gem 'spring-watcher-listen', require: false
gem 'spring', require: false
# ...
end
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Eager load all files so that SimpleCov reports accurate coverage.
Rails.application.eager_load!
# If we are using Spring, then SimpleCov is started in config/spring.rb
unless defined?(Spring)
require 'simplecov'
SimpleCov.command_name 'RSpec'
SimpleCov.start 'rails'
end
if ENV['RAILS_ENV'] == 'test'
require 'simplecov'
SimpleCov.class_eval do
class << self
attr_accessor :spring_preload_result
# Returns the result for the current coverage run, merging it across test suites
# from cache using SimpleCov::ResultMerger if use_merging is activated (default).
# If Spring is used, we merge in coverage from the preloaded Rails app.
def result
return @result if result?
# Collect our coverage result
if running
raw_result = add_not_loaded_files(Coverage.result)
if SimpleCov.spring_preload_result
raw_result = SimpleCov::RawCoverage.merge_results(
SimpleCov.spring_preload_result,
raw_result
)
end
@result = SimpleCov::Result.new(raw_result)
end
# If we're using merging of results, store the current result
# first (if there is one), then merge the results and return those
if use_merging
SimpleCov::ResultMerger.store_result(@result) if result?
@result = SimpleCov::ResultMerger.merged_result
end
@result
ensure
self.running = false
end
end
end
SimpleCov.command_name 'RSpec'
SimpleCov.start 'rails'
# Prevent SimpleCov from writing test coverage after the Spring process exits
SimpleCov.pid = nil
end
Spring.after_fork do
next unless Rails.env.test?
# Ensure that SimpleCov writes test coverage for this process
SimpleCov.pid = Process.pid
end
@MatheusRich
Copy link

How to make this work with Simplecov >= 0.18.0 ? It seems that they removed SimpleCov::RawCoverage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment