News Archive
PhpRiot Newsletter
Your Email Address:

More information

Beyond TDD with PHPSpec

Note: This article was originally published at Planet PHP on 3 August 2011.
Planet PHP

This is the second part of a series about Outside-in Behaviour Driven Development in PHP. The first part introduces outside-in development, and how to execute scenarios with Behat. Read this to catch up with the tools and the example we've used so far, then come back to find out how PHPSpec fits into this picture.

PHPSpec is the first ever PHP BDD framework. It is a port of RSpec to PHP created back in 2007 by PAdraic Brady and Travis Swicegood. Development in this framework stopped for a while and was reignited last August (2010). PHPSpec can be installed via pear, using these commands:

$ sudo pear config-set preferred_state beta $ sudo pear channel-discover $ sudo pear install --all-deps phpspec/PHPSpec

If you are accustomed to unit testing, here is a quick translation sheet for xUnit/xSpec terms:

  • In xUnit we test; in xSpec we describe, so your class names begin with aoDescribea
  • In PHPSpec, the spec file for a class MyClass is named MyClassSpec.php
  • In xUnit we group tests in a TestCase. In xSpec we have examples that are grouped into Contexts
  • In xUnit each method is a test with the prefix test. In xSpec each method is an example, we use the prefix it
  • In xUnit we assert that something work as expected. In xSpec we specify how it should work

We've used Gherkin and Behat to specify how our application is supposed to work. We use PHPSpec to specify the behaviour of our classes. To get you started, let's see a simple example showing this. We are building a class that greets the user with aoHello, World!a. The GreeterSpec.php file would look like this:

class DescribeGreeter extends \PHPSpec\Context { function before() { $this-greeter = $this-spec(new Greeter); } A function itGreetsUsingAHelloWorldMessage() { $message = $this-greeter-greet(); $message-should-be('Hello, World!'); } }

If you already have experience with Unit Testing, the above would look familiar to you. Note that instead of saying: $this-assertEquals('Hello, World!', $message) we say $message

Truncated by Planet PHP, read more at the original (another 28777 bytes)