ruby-on-railsrspecrakesimplecov

How to check RSpec code coverage in Rails application?


I'm working on my very first simple Rails app. And now I just did my homework which I should do before anything else - RSpec tests. I delayed it on purpose because of no experience I even wasn't sure what for and how to do RSpec tests. Finally, I have probably most tests for my models and controllers and it's time for me to think about how much my tests cover the code.

Then I found rake stats, which shows me that:

+----------------------+-------+-------+---------+---------+-----+-------+
| Name                 | Lines |   LOC | Classes | Methods | M/C | LOC/M |
+----------------------+-------+-------+---------+---------+-----+-------+
| Controllers          |   214 |   161 |       4 |      29 |   7 |     3 |
| Helpers              |    12 |    12 |       0 |       1 |   0 |    10 |
| Models               |    17 |    13 |       2 |       0 |   0 |     0 |
| Mailers              |     0 |     0 |       0 |       0 |   0 |     0 |
| Javascripts          |    29 |     3 |       0 |       1 |   0 |     1 |
| Libraries            |     0 |     0 |       0 |       0 |   0 |     0 |
| Helper specs         |    15 |     4 |       0 |       0 |   0 |     0 |
| Controller specs     |   170 |   137 |       0 |       0 |   0 |     0 |
| Model specs          |    78 |    65 |       0 |       0 |   0 |     0 |
+----------------------+-------+-------+---------+---------+-----+-------+
| Total                |   535 |   395 |       6 |      31 |   5 |    10 |
+----------------------+-------+-------+---------+---------+-----+-------+
  Code LOC: 189     Test LOC: 206     Code to Test Ratio: 1:1.1

It shows how many Classes and Methods my controllers and models have. But what I'm missing here is how many are tested. I wish to have it instead of zeros there. At the same time would be nice to know which methods are not covered by tests. Is there a gem that provides that information or some other way to check it?


Solution

  • I'd recommend SimpleCov for this.

    Here's a nice starting configuration for it to put in your spec_helper.rb:

    SimpleCov.start do
      add_filter '/test/'
      add_filter '/config/'
      add_filter '/vendor/'
      
      add_group 'Controllers', 'app/controllers'
      add_group 'Models', 'app/models'
      add_group 'Helpers', 'app/helpers'
      add_group 'Mailers', 'app/mailers'
    end
    # OPTIONAL
    # This outputs the report to your public folder
    # You will want to add this to .gitignore
    SimpleCov.coverage_dir 'public/coverage'
    

    This makes it ignore files in your test, config and vendor folders and groups controllers, models, helpers and mailers under their own tabs in the HTML report.