16.5. Measuring Code CoverageIt is incredibly useful to know what parts of your code are not getting exercised. This helps you to know when you have areas that are lacking in unit tests. In some cases, the coverage tool itself can show you bugs. For example, suppose you have an if statement that "should be" executed about half the time. If you find that it is never executed, that is an easily pinpointed bug. The rcov command-line utility (and its corresponding library) are the work of Mauricio Fernandez. Install it as a gem. To run it in the simplest case, simply invoke it with your program as a parameter: rcov myfile.rb Your program will run, but at the same time, rcov will be gathering statistics. By default, it will create a directory called coverage, where you will find HTML files. The index.html has an overview of the results, and it links to all the sources with the lines highlighted according to whether they were executed. Because of the color coding, it's difficult to show a screenshot of this in grayscale. But the tool is simple to install and run, so you can see your own results in a matter of two minutes. The rcov command, although it is useful with its defaults, does have quite a few command-line parameters (around 30, in fact). You can specify the output directory, patterns for filenames to include or exclude, sorting for the filenames, and more. You can do text mode output of the statistics or even colorized output of the coverage information. I suggest you read the documentation that comes with rcov, do an rcov -h to list all the options, and just have fun. It's also possible to use rcov as a library to write similar analysis tools. Three main classes are exposed in the API:
A discussion of this API is far beyond the scope of this section. Consult the included documentation and start experimenting. |