Functional test helpers for symfony 1.4 code

We you come to write functional tests in symfony 1.4 you can end up with a lot of duplicated code when testing basic things like the routing. To make life easier you can add helper functions to your tests to reduce the amount of duplication, and speed up test writing. So let’s start with the routing example.

If you look at the example on the Symfony documentation for Day 9: The functional Tests you will test code as follows:

// test/functional/frontend/categoryActionsTest.php
include(dirname(__FILE__).'/../../bootstrap/functional.php');

$browser = new sfTestFunctional(new sfBrowser());

$browser->
  get('/category/index')->

  with('request')->begin()->
    isParameter('module', 'category')->
    isParameter('action', 'index')->
  end()->

  with('response')->begin()->
    isStatusCode(200)->
    checkElement('body', '!/This is a temporary page/')->
  end()
;

This is what you start with for auto-generated functional tests, and it is from here that you can add more in depth tests to test your actions and module.

Now the above is ver verbose, and not massively useful if you start duplicating this block to test all the actions in a module so what you can do is make a simple helper function called module_action_check() which would allow you to replace all this code, with a single statement in your test and check the routing and http status.

// test/lib/module_action_check.php

function module_action_check($get, $module, $action, $code)
{
    $browser = new sfTestFunctional(new sfBrowser());

    $browser
        ->get($get)
        ->with('request')
            ->begin()
                ->isParameter('module', $module)
                ->isParameter('action', $action)
            ->end()
        ->with('response')
            ->begin()
                ->isStatusCode($code)
            ->end();
}

You can then use this to reduce the amount of code in your test as follows:

// test/functional/frontend/categoryActionsTest.php
include(dirname(__FILE__).'/../../bootstrap/functional.php');
include(dirname(__FILE__).'/../../lib/module_action_check.php');

module_action_check('/category/index', 'category', 'index', 200);

Obviously this does not check the body, but you can create additional helpers to do that.

Leave a Reply

Your email address will not be published. Required fields are marked *