Sean’s Obsessions


  • I'm a happy Linode customer. This is a Linode 540 VPS. Linode periodically increases RAM and disk while keeping costs steady, which makes them the natural choice.
  • Archives

29 Feb

How the hell do you test a controller?

Testing models is straightforward, see http://bakery.cakephp.org/articles/view/testing-models-with-cakephp-1-2-test-suite

Testing a controller though… Why is there nothing good out there that tells you how to test a controller, other than references to Felix’s work that doesn’t use simpletest?

That said, testing a controller should look something like

- Create controller object
- Call an action
- Poke at the controller to make sure it looks ok.

To test, I baked a controller and put in one action:

<?php
class PrintersController extends AppController {
        var $name = 'Printers';
        function foo() {
                $this->set("something", "some value");
                return 1;
        }
}
?>

I then modified the baked test case (tests/cases/controllers/printers_controller.test.php)

<?php

App::import('Controller', 'Printers');

class PrintersControllerTestCase extends CakeTestCase {
        var $TestObject = null;

        function setUp() {
                $this->TestObject = new PrintersController();
        }

        function tearDown() {
                unset($this->TestObject);
        }

        function testMe() {
                $result = $this->TestObject->foo();
                debug($this->TestObject);
        }
}
?>

After running the test, I could see the methods and variables in the controller. The stuff I could see testing in the controller is mostly the vars that get passed to the view, so after consulting the debugs I changed testMe() to

        function testMe() {
                $result = $this->TestObject->foo();
                $vars = $this->TestObject->viewVars;
                $this->assertEqual($vars["something"],
                     "some value");
                debug($this->TestObject);
        }

$vars is an array of the stuff that’s going to be sent to the view. Logically, if my model tests are correct and I have fixtures set up, the stuff that gets generated by the controller should be predictable and therefore testable.

I also noticed some other entries in the debug output, such as pagetitle. I’m sure there’s more, but this is a good start for now. Wh

Leave a Reply

© 2012 Sean’s Obsessions | Entries (RSS) and Comments (RSS)

Powered by Wordpress, design by Web4Sudoku, based on Pinkline byGPS Gazette