Why You Should Now Be Using PHPSpec

Feb 10, 2014 00:00 · 322 words · 2 minutes read phpspec symfony2 testing

Symfony 2 based applications should be built from test-driven methods. Given the nature of such applications, I found myself wondering if unit testing with phpunit is the right way to go. A Symfony application should implement a specified set of features, and the application should not be viewed from a functional level.

After browsing through Building Quality into a Symfony app I decided to take the jump and specify my implementation instead of just the functionality. This is easily accomplished with PHPSpec.

The switch

To switch the default Symfony project to PHPSpec I first recommend installing Composer.

Using Composer we create a project template (based on Symfony2 LTS):

$ composer create-project symfony/framework-standard-edition path/ "2.3.*"

Next we will add PHPSpec and friends:

$ composer require --dev "phpspec/phpspec:2.0.*"
$ composer require --dev "phpspec/prophecy:1.2.*"
$ composer require --dev "henrikbjorn/phpspec-code-coverage:1.0.*@dev"

This will add PHPSpec along with the mocking framework prophecy, and the extension for generating coverage reports – which you may want to see, right?

Final call

You can – and should – add a custom configuration for PHPSpec to your project since it allows you to tune output, enable extensions, and to call spec suites for specific bundles.

The following phpspec.yml configuration file is built for the default AcmeDemo bundle and enables the code coverage extension with a default configuration.

extensions:
    - PhpSpec\Extension\CodeCoverageExtension

code_coverage:
  format: html
  output: .qa/coverage

formatter.name: pretty

suites:
  AcmeDemoBundle:
    namespace: Acme\DemoBundle
    spec_path: src/Acme/DemoBundle

Now you can start creating specs in src/Acme/DemoBundle/spec/ for each par of the bundle, and once done, you can run the test suite:

$ php bin/phpspec run

Check out the PHPSpec manual, and make friends with it. It might take a while, but you will soon notice that you find yourself only producing the code you really need, instead of mass producing what you do not.

Expect to see more about PHPSpec soon. One hint as a preview: do not try to spec abstract classes, spec the implementations only!

Comments powered by Disqus