gignus.com

Web development

Cake Unit Testing: Dropping and recreating tables on each test takes too much time

Created: 2008-02-07 14:25:17, last updated: 2008-02-07 22:48:47

In my last post, I extended the CakeWebTestCase class to recreate the tables instead of truncating them on each test. Now I think this might not be a good idea.

At first I liked it, but when the quantity of tests grew up, recreating the tables took too much time and my tests began to fail. I have to add a sleep of two 2 seconds to make them work, and that's a lot of time to spent on something that should be immediate.

So here is what I do now:

  1. Add a new property: $methods to the class, with startcase and endcase (following CakeTestCase convention), and override Simpletest's getTests() to make it call them on the start and end of each test.
  2. Call the fixtures loader start method on startCase and the end method on endCase.

class CustomCakeWebTestCase extends  CakeWebTestCase  {
	public $methods = array('startcase', 'endcase');
	
	function startCase() {
		$this->fixturesLoader = new FixturesLoader( am($this->fixtures, $this->defaultFixtues) );
		$this->fixturesLoader->start();		
	}
	
	function endCase() {
		$this->fixturesLoader->end();
	}
	
/**
 * Gets a list of test names. Normally that will be all internal methods that start with the
 * name "test". This method should be overridden if you want a different rule.
 *
 * @return array	List of test names.
 *
 * @access public
 */
	function getTests() {
		$methods = parent::getTests();
		$methods = am(am(array('startCase'), $methods), array('endCase'));
		return $methods;
	}
	
}

Now, the tables are generated on the beginning and end of each test case. It's not as safe as before, but we can live with the risk. What risk? Well I can only think of one right now: when using transactions if you start one and you don't close it, the truncating of the table may fail, but that's easily fixable by checking for an open transaction on the tearDown() method and closing it.

0 comments

Cake Unit Testing: Dropping and recreating tables on each test takes too much time

Add Comment:

Copyright © 2007 Matias Lespiau - Powered by CakePHP