How To Get Accurate Test Coverage With SimpleCov, Spring, and Rails
Here’s how you can get accurate SimpleCov test coverage while using Spring to preload your Rails application.
If you’d like to read more about how I figured this out, I’ve written a longer blog post that goes into a lot more detail: How I Figured Out A Test Coverage Issue With SimpleCov And Spring.
The following code has been tested with these library versions:
- spring:
2.0.2
,2.1.0
- simplecov:
0.16.1
,0.17.1
- rspec:
3.8.0
,3.9.0
- rails:
5.2.3
Gemfile
Prevent spring
from being automatically required:
config/spring.rb
Configure Spring and monkey-patch SimpleCov:
config/environment.rb
Add this code to config/environment.rb
:
spec/spec_helper.rb
Add this code to the top of spec/spec_helper.rb
:
spec/rails_helper.rb
Add these lines to the top of spec/rails_helper.rb
:
That’s it! Now you should see accurate test coverage whenever you run your RSpec tests with Spring.
Before:
After:
I am planning to open an SimpleCov issue to get some feedback about this approach, and it would be great SimpleCov and Spring just worked together by default. In the meantime, you can use this code to get things working.
If you’d like to learn more about how I investigated this issue, you can check out this longer write-up that goes into a lot more detail: How I Figured Out A Test Coverage Issue With SimpleCov And Spring.