Test Driven Development in PHP - Page 6

Designing by modifying existing code is called "Refactoring". It is an essential step in Test Driven Development as without it we lose the vital design phase altogether. I have deliberately exaggerated the poor design so far just to illustrate the process.

I actually got this right on the first go, but I suspect that this was a fluke. More likely I would have had a failure, such as forgetting to trim the trailing carriage return. In this case just do a hack to add it, rerun the tests, and then just focus on only that issue. It is much easier to shuffle the code about with the tests to protect you.

What I have done here is moved in the smallest possible steps. One of the joys of this process is that we can tune the step size as we go. If we get lot's of easy passes, take bigger steps. If you get a failure you don't expect, slow down and do less work each cycle. The cycle is red, green, refactor.

Tests as Documentation

We repeat the cycle until we cannot think of any more sensible tests to add. With five more cycles we get the following test case...