3.2. Source Code Examples As Documentation

Repeatable tests are all fine and well, but it turns out that they also serve another purpose. Just as a picture is worth a thousand words, in programming a good example of how to use your code is also worth a thousand words. Your repeatable examples, which make great future tests, also act as a guide for users and other programmers in how to correctly use your source code.

It's here where I can introduce the idea that the traditional "test" of Unit Testing and Test-Driven Development can simply be referred to as an example. Each example you write explains one more facet of behaviour your source code is capable of, how to make that behaviour occur, and what it's effects are. In Behaviour-Driven Development, each such example can also be thought of as a specification (or "spec" for short).

In BDD, which promotes the use of a language more readily readable and accessible for coding examples, the value of your specs as documentation is improved using a fluent Domain Specific Language. Consider the differences which make the second example below more clear and legible than the first example.

Example 3.1. Example with PHPUnit

$logger = new Logger;
$this->assertTrue($logger->hasFile());

Example 3.2. Example with PHPSpec

$logger = new Logger;
$this->spec($logger)->should->haveFile();

Because code examples make for great documentation (not just tests) it's better to have examples which follow the natural flow of plain English to improve their readability and clarity. Not only that but done properly any set of examples should be translatable back into their plain text form so you have a sentence (based on our earlier examples) of:

Logger

- should have a file

Before we continue, remember that BDD is not just TDD with "should" instead of "assert". There are other reasons for BDD's raison d'etre besides a simple language differential from TDD.