Test-driven development

Test-driven Drupal development

October 24, 2008

Drupal's implementation of SimpleTest-style testing is an amazing tool for developing complex applications. When code is complex enough, a simple change can break things in unexpected places, but with good test coverage, this breakage can quickly be discovered and fixed. The same goes for deploying Drupal sites. By default SimpleTest creates a parallel test database from the ground up, meaning that it installs a brand new Drupal site, rather than copy the instance of Drupal it is installed on. This is all well and good for module development, and maintaining a solid core, but when it comes to testing complex site configurations, it would be nice to be able to test that all the installed modules, configured in such and such a way, are all playing nicely together. Taking this one step further, for a really complex site, it becomes possible to write a set of acceptance tests before site configuration even starts. Knowing that these tests must eventually pass can significantly focus and drive the development work.

That's where overriding the DrupalWebTestCase setUp() function comes into play. SimpleTest will run the setUp() function as defined in the DrupalWebTestCase() class unless the current test case has an overriding setUp() function. Some existing tests append additional functionality during set up, but most usually call the parent method, which is responsible for installing that fresh instance of Drupal.
To copy the existing set up, the parent function can be overridden on a per-test-case basis:

  class MyModuleHelperTestCase extends DrupalWebTestCase {
 
    /**
     * Implementation of setUp().
     */
    function setUp() {
      // Here the existing Drupal instance will be cloned.
    }

By defining the function here, the parent method won't be called by SimpleTest. Also note that this helper test case can be called by additional test cases so that the cloning of the database doesn't need to be re-coded for each test case. In order to clone the existing set up, the database schema is needed. Once we have the schema, it is looped through, creating identical tables, and then populating them: