Basic TDD in Rails : Configuring SimpleCov Test Coverage Gem
Learn how to use SimpleCov gem to generate test coverage report.
Why do we need a coverage report tool when we know that our test coverage will be 100% when we write test first? In a real-world Rails app, you will have gems, Rails engines and other third-party libraries that you need to customize. This can lead to gaps in your test coverage. By running the test coverage reports before you checkin the code, you can write tests for the code with no coverage.
Add simplecov gem to the test group.
gem 'simplecov', :require => false
I have also cleaned up the other gems like this:
group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' gem 'rspec-rails', '~> 3.2' end group :test do gem 'capybara' gem 'selenium-webdriver' gem 'database_cleaner' gem 'simplecov', :require => false end
This now separates all the test related gem from the development and test group. I have also changed the
rspec-rails version to 3.2.
Add the lines:
require 'simplecov' SimpleCov.start
to the top of the
$ rake spec
This will run all your tests.
Open the coverage/index.html in a browser. You can see we have 99.32 % test coverage. For some reason it thinks
rails_helper.rb configuration for
database_cleaner is not covered. To fix this change the top two lines in the
spec_helper.rb to :
require 'simplecov' SimpleCov.start 'rails'
Now the test coverage will be 100%.
In this lesson we installed and configured
simple_cov gem to generate test coverage reports. You also learned why we need to use a test coverage tool in our projects.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview