views:

182

answers:

1

I'm starting to write unit tests using the CakePHP framework and SimpleTest. The documentation describes a problem with the testAction method when your controller redirects the browser to another page. There is a hopeful note with a link to a possible fix, but the link is broken.

Has anybody gotten this working? Know how to find where that broken link should point?

I found a discussion of using partial mock objects to override the redirect call, but that doesn't seem to work with the testAction method. I suspect I'd have to somehow register the mock controller with the dispatcher.

Here's a similar question on Google groups.

A: 

I got something to work, so I thought I'd post it here. I'm not sure if I'm happy with it yet.

If you want to be able to test a redirect, change this:

$this->redirect(array('action'=>'index'));

to this:

$this->redirect(array('action'=>'index'), null, false);
return 'redirected to index';

Now your test can look something like this:

$data = array(...);
$result = $this->testAction(
    '/people/edit/1',
    array('method' => 'post', 'data' => $data));
$this->assertEqual(
    'redirected to index',
    $result);

The problem with the controller's redirect method is that it calls exit() by default, and that exits out of the entire test suite. This version passes false to the redirect method's $exit parameter, and then uses return instead of exit(). The return value is just something for the test case to validate if you like, although it is echoed to the browser along with the redirect header. As long as it's a small message, though, I don't see any problem with that.

There doesn't seem to be any significant code that might execute after the controller method when we call return instead of exit(). A quick test shows that the page behaves normally.

Don Kirkby