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:
- Introduction
- Tools overview
- Test Driven Development
- TDD: just do it!
- spec BDD
- phpspec: a quick tour
- Behavior Driven Development: story BDD
- Behat: a quick tour
- 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.
Introduction
phpspec automates the Test Driven Development (TDD) and spec BDD process by:
- allowing you to generate the specification
- then allowing you to generate the code from it
It also forces you to follow good practices:
- you can only test non-static public methods
- you cannot generate a code coverage report
It also tries to be less verbose, as you'll see in the next sections.
Installation
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.
Process
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:
- here's the complete list of assertions
- here's how to customize the specification and code tempaltes
- here's how to configure phpspec
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).
Conclusion
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