Loïc Faugeron Technical Blog

phpspec: a quick tour 11/03/2014

TL;DR: jump to the conclusion.

This article is part of a series on Tests in general and on how to practice them:

  1. Introduction
  2. Tools overview
  3. Test Driven Development
  4. TDD: just do it!
  5. spec BDD
  6. phpspec: a quick tour
  7. Behavior Driven Development: story BDD
  8. Behat: a quick tour
  9. Conclusion

The last article might have seemed too abstract. Fortunately, this one will be much more concrete! We'll present phpspec, a spec BDD tool for PHP.


phpspec automates the Test Driven Development (TDD) and spec BDD process by:

It also forces you to follow good practices:

It also tries to be less verbose, as you'll see in the next sections.


Simply install phpspec using Composer:

composer require --dev 'phpspec/phpspec:~2.0@RC'

At the time I write this article, phpspec is in Release Candidate, but don't worry: I've been using it since the beta version and I've never had any trouble.


First, bootstrap and complete the specification:

phpspec describe 'Fully\Qualified\Classname'
$EDITOR spec/Fully/Qualified/ClassnameSpec.php

Then bootstrap and complete the code to make the tests pass:

phpspec run
$EDITOR src/Fully/Qualified/Classname.php
phpspec run

Finally refactor, but keep the tests passing:

$EDITOR src/Fully/Qualified/Classname.php
phpspec run

I've found that Marcello Duarte, the creator of phpspec, talks really well about it in his presentation Test, transform, refactor.

I advise you to have a look at his slides, as they explain everything you should now about the red, green, refactor cycle.

A tour of the documentation

Surprisingly, the documentation is complete and small:

There's nothing missing in these docs!

Prophecy, the test double framework

Unlike PHPUnit, phpspec uses an external library for its test doubles: prophecy (but you can still find how to use it in the documentation).


phpspec generates specification and code boilerplates for you. It forces you to concentrate on the class behavior rather than on the implementation and it provides a non verbose API. Even its documentations is complete and small!

I hope you enjoyed this article, be sure to tweet me what you think about it ;) .

Reference: see the reference article