Lesson Weekend

We always emphasize the importance of thorough test coverage. As our applications grow in size and complexity, we — and anyone looking at our code — must confidently rely on our tests to ensure that our application is in working order. Ideally, our unit and integration tests should touch every line of code. If not, we are often either missing tests or we may have unnecessary code that needs to be removed.


Thankfully, there's a tool to help us determine how well our tests are covering our codebase. The SimpleCov gem is a code analysis tool that runs when we run RSpec and determines what percentage of our code has been tested.

Implementing SimpleCov

To implement SimpleCov, add it to the Gemfile and run $ bundle:

group :test do
  gem 'shoulda-matchers'
  gem 'capybara'
  gem 'launchy'
  gem 'simplecov', require: false

In the spec_helper.rb file, add:

require 'simplecov'


RSpec.configure do |config|

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true

Note: All comments have been removed from the file for demonstration purposes.

Finally, we'll need to change a line in the /config/environments/test.rb file so SimpleCov reviews all project code, not just the code specs are written for:

config.eager_load = true

Running SimpleCov & Reading Results

Now, when you run $ rspec in the terminal, SimpleCov provides the following information after the testing details:


Finished in 0.74243 seconds (files took 4.98 seconds to load)
8 examples, 0 failures

Coverage report generated for RSpec to /Users/kelly/Code/rails/to-do/coverage. 135 / 157 LOC (85.99%) covered.

85.99%?!? What's missing? As indicated, a coverage report is generated each time RSpec is run. It can be found in a new coverage folder in the project directory. To see the details, open the index.html file in the browser.

SimpleCov Results

Judging from the results, there are lines of code in the controllers that have not been touched in our testing. This either means we have incomplete testing OR there is code in place that is no longer needed. Often, as code is updated, previous code becomes obsolete but doesn't get deleted. Any unused code should be removed or commented out.

In this example, the else statements in the conditional lines under the new and update actions of the controllers do not have tests.

Ideally, our SimpleCov score would be 100%. Aim for 100% in all of your testing. For anything less, determine the cause and improve your test coverage or clean up your code as needed.

Lesson 3 of 27
Last updated August 7, 2022