A php toolset to drive emergent
design by specification.

phpspec
repository
phpspec
manual

Spec BDD with phpspec

phpspec is a development tool, designed to help you achieve clean and working PHP code by using a technique derived from test-first development called (spec) behaviour driven developement, or SpecBDD.

The technique consists of describing the next object behaviour (spec) you are about to implement, using a tool like phpspec, then writing just enough code to quickly satisfy that specification and finally stopping to refactor the last increment, allowing the emergent design to guide the direction. This is done in small iterative steps.

Installation

phpspec is a php 5.3 library that you’ll have in your project development environment. Before you begin, ensure that you have at least PHP 5.3.1 installed.

Method #1 (Composer)

The simplest way to install phpspec with all its dependencies is through Composer:

Create composer.json file in the project root:

{
    "require-dev": {
        "phpspec/phpspec": "*"
    },
    "config": {
        "bin-dir": "bin"
    },
    "autoload": {"psr-0": {"": "src"}},
    "minimum-stability": "dev"
}

Then download composer.phar and run install command:

$ curl http://getcomposer.org/installer | php
$ php composer.phar install --dev

Everything will be installed inside vendor folder and executable will be linked into bin folder.

SpecBDD and TDD

There isn’t any real difference between SpecBDD and TDD. The value of using a xSpec tool instead a regular xUnit tool for TDD is language. The concepts and features of the tool will keep your focus on the “right” things. The focus on verification and structure as opposed to behaviour and design is, of course, a valid one. We happen to find that the latter is more valuable on the long run. It was also the intention of early users of TDD.

SpecBDD and StoryBDD

While with StoryBDD tools like Behat are used to understand and clarify the domain - specifying feature narratives, its need, and what do we mean by them - with SpecBDD we are only focused on the how: the implementation. You are specifying how your classes will achieve those features.

A good StoryBDD tool will let the business talk the domain language and drive the development by putting the focus on what really matters first.

Once you know why you are adding a feature and what it will be, it’s almost time to write code. But not yet! Adding code without a way to validate that it serves the specs just means you will have to go back and rework it, so that it does match the spec. And the later you find out you missed the requirement or added a bug, the harder and more expensive it is to fix. Kent Beck also adds that describing the code before you actually write it is a fear management technique. You don’t have to write all the code, just the spec of the next thing you want to work on. That executable spec will then guide you to what code you need to write. Once you do that, then what you have is a chance to refactor. Because if you change the behaviour of your code the specs will go red. So you spec so that you can refactor, or allow the design of your code to emerge in a sustainable way. SpecBDD tools are designed to guide you in the process, or at least not stand on the way.

It’s valid to assume that StoryBDD and SpecBDD used together are a very effective way to achieve highly customer-focused software.

Getting Started

Say we are building a tool that converts Markdown into HTML. Well, that’s a large task. But I will work on simple things first and a design will emerge that will reach all the necessary features. Even though I have all the specs from the customer (we have done all our Behat feature files nicely), I know I will discover new things I will need, as soon as I sit down to write my classes.

What is the simplest thing I want to add? It should convert a string line into a paragraph with HTML markup, i.e. “Hi, there” would become “<p>Hi, there</p>”.

So let’s do this. Well, not the boring bits. Let phpspec take care of the boring stuff for us. We just need to tell phpspec we will be working on the Markdown class.

$ bin/phpspec desc Markdown
Specification for Markdown created in spec.

You can also specify a fully qualified class name. Don’t forget that if you use backslashes you need to pass the class name inside double quotes. Alternatively you could use forward slashes and skip the quotes. phpspec will create the folder structure following PSR standards.

Ok. What have we just done? phpspec has created the spec for us. You can navigate to the spec folder and see the spec there:

<?php

namespace spec;

use PhpSpec\ObjectBehavior;

class Markdown extends ObjectBehavior
{
    function it_should_be_initializable()
    {
        $this->shouldHaveType('Markdown');
    }
}

That’s awesome! phpspec created the spec for me.

But first, let’s see what we have here. Our spec extends the special ObjectBehavior class. This class is special, because it gives you ability to call all the methods of the class you are describing and match the result of the operations against your expectations.

Examples

The object behavior is made of examples. Examples are encased in public methods, started with it_. or its_. phpspec searches for such methods in your specification to run. Why underscores for example names? just_because_its_much_easier_to_read than someLongCamelCasingLikeThat.

Matchers

Matchers are much like assertions in xUnit, except the fact that matchers concentrate on telling how the object should behave instead of verifying how it works. It just expresses better the focus on behaviour and fits better in the test-first cycle. There are 5 matchers in phpspec currently, but almost each one of them has aliases to make your examples read more fluid:

  • Identity (return, be, equal, beEqualTo) - it’s like checking ===
  • Comparison (beLike) - it’s like checking ==
  • Throw (throw -> during) - for testing exceptions
  • Type (beAnInstanceOf, returnAnInstanceOf, haveType) - checks object type
  • ObjectState (have**) - checks object is** method return value

How do you use those? You’re just prefixing them with should or shouldNot depending on what you expect and call them on subject of interest.

Now we are ready to move on. Let’s update that first example to express my next intention:

<?php

class Markdown extends ObjectBehavior
{
    function it_converts_plain_text_to_html_paragraphs()
    {
        $this->toHtml("Hi, there")->shouldReturn("<p>Hi, there</p>");
    }
}

Now what? We run the specs. You may not believe this, but phpspec will understand we are describing a class that doesn’t exist and offer to create it!

$ bin/phpspec run

> spec\Markdown

  ✘ it converts plain text to html paragraphs
      Class Markdown does not exists.

         Do you want me to create it for you? [Y/n]

phpspec will then place the empty class in the directory. You run your spec again and... OK, you guessed:

$ bin/phpspec run

> spec\Markdown

  ✘ it converts plain text to html paragraphs
      Method Markdown::toHtml() not found.

         Do you want me to create it for you? [Y/n]

What we just did was moving fast through the ambar state into the red.

<?php

class Markdown
{

    public function toHtml()
    {
        // TODO: implement
    }
}

We got rid of the fatal errors and ugly messages that resulted from nonnexistent classes and methods and went straight into a real failed spec:

$ bin/phpspec run

> spec\Markdown

  ✘ it converts plain text to html paragraphs
      Expected "<p>Hi, there</p>", but got null.


1 examples (1 failed)
284ms

According to the TDD rules we now have full permission to write code. Red means “time to add code”; red is great! Now we add just enough code to make the spec green, quickly. There will be time to get it right, but first just get it green.

<?php

class Markdown
{

    public function toHtml()
    {
        return "<p>Hi, there</p>";
    }
}

And voilà:

$ bin/phpspec run

> spec\Markdown

  ✔ it converts plain text to html paragraphs

1 examples (1 passed)
247ms

I will leave the explanation of the whole TDD/SpecBDD cycle for a blog post. There are heaps of resources out there already. Here are just a couple for you look at:

  1. The Rspec Book Development with RSpec, Cucumber, and Friends by David Chelimsky, Dave Astels, Zach Dennis, Aslak Hellesøy, Bryan Helmkamp, Dan North
  2. Test Driven Development: By Example Kent Beck

Prophet Objects

Stubs

When you describing an object, you want your focus to be just there, in the object. You don’t want to wander off to start describing collaborators. You can very easily tell phpspec that there will be collaborators and stub their behaviour so you can describe your object message exchange with them.

<?php

namespace spec\Markdown\Formatter;

use PhpSpec\Specification;

class EndOfListFormatter extends ObjectBehavior
{
    /**
     * @param Markdown\Stream $stream
     */
    function it_adds_a_end_of_list_to_markup($stream)
    {
        $stream->getNextLine()->willReturn("");
        $this->format(" * Hi, there", $stream)->shouldReturn("</li></ul>");
    }
}

To stub the behaviour of Markdown\Stream::getNextLine() we just need to pass it to the example, using widely used phpdoc notation, and configuring the stub is merely stating what it should return: ->willReturn("").

Mocks

In addition you will need to verify a message was sent to a collaborator during the normal execution of a method. You can specify a mock expectation with ->shouldBeCalled()

<?php

namespace spec;

use PhpSpec\Specification;

class MyObject extends ObjectBehavior
{
    /**
     * @param SomeEvent $event
     * @param SomeSubscriber $subscriber
     */
    function it_formats_the_string_as_a_header_if_underline_with_single_dashes($event, $subscriber)
    {
        $subscriber->onChange($event)->shouldBeCalled();

        // when
        $this->addSubscriber($subcriber);
        $this->doWhatever($event);
    }
}

Let and Let Go

phpspec implements the symmetric setup and tear down using the let and letgo methods.

<?php

class EverChangingWorld extends ObjectBehavior
{
    function let($die)
    {
        $die->beAMockOf('Die');
        $this->beConstructedWith($die);
    }

    function it_live_and_let_die($die)
    {
        $this->liveAndLet()->shouldReturn($die);
    }

    function letgo()
    {
        // release any resource
        // put the system back into the state it was before the example
    }
}

Cookbook

Other useful resources for learning/using phpspec: