Tuesday, 5 May 2015

Know your Coverage with SimpleCov - Part 1

As I am digging deeper into Rails I am also discovering new ways which help maintaining my code. One of which I have come to believe is code coverage. Its the percentage of code which has been covered by the unit tests you've written. Where a 100% code coverage doesn't ensure that your test suite is absolutely bulletproof, a poorly covered one promises you bugs which you would never see coming.

So I tried this brilliant gem, SimpleCov, a complete code coverage suite which gives you options to filter, group, merge and format the results. Here's how you setup simplecov in your project:

gem 'simplecov', :require => false, :group => :test

Add the above line in your Gemfile and run bundle install, which will install the required gems.
Now in your Rails project, open the rails_helper.rb file and add these lines above any other require statement.

require 'simplecov'
SimpleCov.start

Now you’re all setup and good to go! Run your tests and run this command

$ open coverage/index.html

You can also configure simplecov by adding filters to it. You probably don’t want the spec or the config files to be included in your coverage results, here is how you do it.

add_filter "/spec/"
add_filter "/config/"

You can also group your coverage results to be displayed in different tabs, like you can group controllers, models, views, helpers, etc.

add_group 'Controllers', "app/controllers"
add_group 'Models', "app/models"

The complete simplecov code snippet now looks like this:

require 'simplecov'
SimpleCov.start do
add_filter "/spec/"
add_filter "/config/"

add_group 'Controllers', "app/controllers"
add_group 'Models', "app/models"
end

Now its time for you to go ahead and cover some code!

No comments:

Post a Comment