Mon Feb 10, 2014

These are roughly 400 words, you could read this in about 2 minutes.

BDD based testing and Symfony is fun, trust me.

Symfony 2 based applications usually should be built driven by tests. But given the nature of such applications I found myself wondering, if unit testing with phpunit really is the right way to go. Why? Because a Symfony application usually should implement a specified set of features, and we should not be looking at our application from a functional level.

Thus after browsing through Building Quality into a Symfony app I decided to take the jump, and specify my implementation rather than to just cover functionality. This is done easily with PHPSpec.

The switch

Now let us switch the default Symfony project to PHPSpec. First I recommend to install 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 also allows 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.

File: phpspec.yml
extensions: - PhpSpec\Extension\CodeCoverageExtension code_coverage: format: html output: .qa/coverage 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 sooner or later notice that you switch from mass producing code to only producing what is really needed.

Expect to see more about PHPSpec soon. One hint ahead of time: do not try to spec abstract classes, spec the implementations only!

Tagged with: Symfony2 phpspec Testing

All code snippets in this post are made available to use under the MIT Licence.


comments powered by Disqus