Thursday, 7 May 2015

Know your Coverage with SimpleCov - Part 2

I'm back with another session of simplecov, but if you haven't read the first part, you might want to give that a read first. Assuming that you have a basic knowledge of code coverage and simplecov, let's get started with today's topic which is more about configuring than simplecov itself.

We will be creating custom Rake Tasks which will allow us to separately run specs and know the coverage for our models, controllers, helpers and other things. Normally what you'll see is that when we run the controller specs, a significant amount of models are also covered, but we don't want that.

Now let's create a coverage.rake file under lib/tasks/ in your project and add these lines:

namespace :spec do
namespace :coverage do
end
end

You can set environment variables and using those as the conditions you can run specific specs as you like. Let's open up rails_helper/spec_helper file and make these changes to your simplecov configuration.

add_group 'Models', "app/models"

becomes

if ENV['COVERAGE_PROFILE] == 'models'
add_filter "app/controllers/"
add_group 'Models', "app/models"
end

and

add_group 'Controllers', "app/controllers"

becomes

if ENV['COVERAGE_PROFILE] == 'controllers'
add_filter "app/models/"
add_group 'Controllers', "app/controllers"
end

Now head over to coverage.rake file, and write a rake task within namespace :coverage to exclusively run your model specs and its coverage.

desc "Create Models coverage"
task :models do
ENV['COVERAGE_PROFILE'] = 'models'
Rake::Task['spec:models'].invoke
ENV['COVERAGE_PROFILE'] = nil
end

Run the following command in terminal, followed by open coverage/index.html

$ rake spec:coverage:models

Similarly, you can also write another rake task to run your controller specs. Happy coding!

No comments:

Post a Comment