Chapter 5. Writing Specs with PHPSpec

Table of Contents

5.1. Specs, Examples and Contexts
5.2. Before Writing Code, Specify Its Required Behaviour
5.2.1. Explaining the PHPSpec Spec Layout
5.2.2. The Code To Implement The New Filesystem Logger Specification
5.3. The Spec Domain Specific Language (DSL)
5.3.1. The Actual Value Term
5.3.2. The Expectation Term (Should or Should Not)
5.3.3. The Matcher Term

5.1. Specs, Examples and Contexts

The terminology used throughout Behaviour-Driven Development is focused entirely on the concept of describing behaviour. This alleviates any misunderstanding from attempting to describe the process of Test-Driven Development in terms of tests - a counterintuitive notion for many programmers.

The terms Spec and Example are almost used interchangeably. While a Spec refers to a single behavioural requirement, often captured as a simple sentence of the form "it should do something", an Example refers to the the entire method within PHPSpec which demonstrates this Spec in code. If you take the example below, the spec is the line of code commencing with $this->spec() and the example is the entire public method which shows how this spec is achievable

Example 5.1. A Spec in a PHPSpec Example Method

public function itShouldHaveScoreOfZero()
{
    $bowling = new Bowling;
    $bowling->hit(0);
    $this->spec($bowling->score)->should->be(0);
}

A more difficult concept is that of a Context. In brief a Context is the set of conditions prevailing at the time we are specifying behaviour. Above, our Bowling example assumes we've just started a new game. This is the Context all our Specs in the same class would share. Later we might want a game which is finished, or partially played. Each different Context helps you explore how behaviour changes under different conditions.