3.3. Writing Examples (Specs) Before Writing Code

As we move up the chain of practices, we eventually reach a point where we have an epiphany. If our examples/tests make such great documentation, describe the behaviour of our classes and applications, and are repeatable over and over, then what if instead of writing pages of planning documentation we just write some examples first, and then write the code to agree to them?

This approach is where Test-Driven Development enters the fray, with the infamous warcry of "Test first!". Since PHPSpec is a Behaviour-Driven Development framework we'll replace this with a "Spec first!" cry.

3.3.1. Why Write Examples First?

The reasoning behind writing examples first is really simple.

The first effect is to force us to face the problem at hand and make us think about what we're doing. It's all too easy to just start coding without a firm idea and get lost before you've even written your first spec or test. I'm sure we've all been there more than once! Writing an example on the other hand means we have to immediately start looking at how the public API will work, how the logic flows between components, the range of output we really need, the logic we may require for an implementation.

The second effect is that doing this in small steps lets us write better code. The code resulting from the structured repetition of small steps - specify, write example, write implementing code, refactor, and rewind - leads to code which has a superior design, is more easily maintained, is usually simpler and clearer, and will generally have fewer bugs as a result.

There are lots of other advantages, but perhaps the best one is confidence. Improved confidence in your design, your code quality, your own skills as a programmer, your complete fearlessness when faced with change, and let's not forget the confidence other programmers and users will have in well designed and tested source code.

3.3.2. The Workflow of BDD using PHPSpec

The process of applying BDD to your coding methodology. Remember to execute your examples once written to ensure they first fail, and during implementation until you're successfully passing them.

  1. Identify a valuable behaviour you want to implement

  2. Describe it in plain text in the form "it should ... ", i.e. a specification

  3. Write one or more specs/examples for the "it should" components of your specification

  4. Implement the behaviour you've just described in the specification

  5. Refactor the implemented code if needed

  6. Return to Step 1

We'll cover this in greater detail when explaining exactly what Behaviour-Driven Development is later. The steps are very similar to the TDD variant of write test, write code, refactor except there's also a focus on the documentation/specification aspect and we're not discussing Testing (that specs make good tests is coincidental to the true purpose of BDD which is to improve design).