Hi, one problem which is faced by people trying to use the testAction method in their controller’s tests is the occurence of redirects in the actions. There are some solutions on the web for this problem. For example, some people like to call the methods directly from an instance of the controller.

Anyway, for those like me, who find the testAction method useful and  still want to use it, I’m using a simple solution for this problem (perhaps I borrowed something from the web, but I sincerely don’t remember from where). The nice part is that you can check the flash messages defined in the controller, which I think is useful.

The  first step is to define a constant in the WEBROOT/test.php file. I use the following sentence:

define('CAKEPHP_UNIT_TEST_EXECUTION', true);

Then, in my (app_)controller I overwrite the redirect method to check if I’m running tests:

function redirect($url=NULL, $code=NULL) {
    if (defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
      $this->set('TEST_REDIRECTED_URL', $url);
      $flash = $this->Session->read('Message.flash');
      $this->set('TEST_REDIRECTED_FLASH', $flash);

      if (isset($flash['message'])) {
        $this->set('TEST_REDIRECTED_MESSAGE', $flash['message']);
      }
    } else {
      parent::redirect($url, $code);
    }
  }

That’s all guys. Now you can go check your flash messages writing tests like this:

 function testMyControllerAction() {      
      $result = $this->testAction('/mycontroller/action',
        array(
           'return' => 'vars'
        )
      );

      $this->assertTrue($result['TEST_REDIRECTED_MESSAGE'] ,"The flash message I'm expecting");
    }

Nice? What do you think? I don’t know. Any flaws? I’m waiting for your comments :P