Sean’s Obsessions

Sean Walberg’s blog

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:


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)


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

Comments

I’m trying something new here. Talk to me on Twitter with the button above, please.