Chapter 3. Introduction

Table of Contents

3.1. Testing Your Code
3.2. Source Code Examples As Documentation
3.3. Writing Examples (Specs) Before Writing Code
3.3.1. Why Write Examples First?
3.3.2. The Workflow of BDD using PHPSpec
3.4. PHPSpec And BDD In Context

3.1. Testing Your Code

How do you currently test code?

The most obvious means of testing PHP code is to save it to a file and browse to it in your web browser. If the output of the script seems correct then your test has been successful. A variation on this theme when testing functions or classes which don't have direct output is to insert var_dump() and echo statements to reveal the content of variables. Another variation is interacting with a completed application to check things work as expected.

These methods of testing are extremely easy but they bely a serious problem. You cannot easily repeat these same tests without a lot of effort. It's in avoiding this effort, and making tests or examples repeatable that makes PHPSpec a valuable tool. I'm not going to exclude SimpleTest, PHPUnit or PHPT from that either - familiarity with more than one framework in PHP is always advisable.

Using a framework like PHPSpec allows you to write examples which are repeatable. These automatic tests can be executed time and time again using a quick command line call or browser refresh. Repeatable testing however is not where it all ends.