Switch your database configuration based on some criteria

Published on and tagged with cakephp  configuration  database  testing  tip

Currently, I am experimenting with unit tests. These tests should use an own database. And so I defined a “test” configuration in app/config/database.php:

var $test    =  array('driver'    => 'mysql',
                      'connect'  => 'mysql_pconnect',
                      'host'     => 'localhost',
                      'login'    => 'user',
                      'password' => 'password',
                      'database' => 'project_name-test',
                      'prefix'    => '');

But it does not automatically use the “test” configuration when I run a test. So I wrote a constructor for app/config/database.php based on the idea from http://wiki.cakephp.org/tutorials:change_database_config, which switches the database configuration based on the request url (thanks to gwoo for the hint):

function __construct () 
{
    if (strstr($_SERVER['REQUEST_URI'], '/tests')) 
    {
        $this->default = $this->test;
    }
}

5 comments baked

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License