Section 16.6. Measuring Performance


16.5. Measuring Code Coverage

It 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:

  • Rcov::FileStatistics is used to distinguish between executable statements and comments (and refine the coverage statistics).

  • Rcov::CodeCoverageAnalyzer is used to trace execution and return coverage and execution count information.

  • Rcov::CallSiteAnalyzer is used to determine where methods are defined and where they are called.

A discussion of this API is far beyond the scope of this section. Consult the included documentation and start experimenting.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net