Codeception acceptance not using test DB

(M Marsella) #1

Hi all, I am starting with codeception, so please bear with me if this is just a silly question!

I have a model User that is routed to two different db connections depending on the environment:

public static function getDb() {

    if (YII_ENV_DEV || YII_ENV_TEST) {

        return \Yii::$app->db;

    } else {

        return \Yii::$app->dbOther;



This works beautifully when I use the application normally. In the test configuration file config.php, I have:

    'db' => [

        'dsn' => 'mysql:host=itpgrfa;dbname=test_db',

        'username' => 'test',

        'password' => 'test',


If I print the app configuration array, I see that the ‘db’ entry is correctly replaced with the test DB. However, when running the tests, the real user tableis used and not the test one. I did some debugging and it appears that the if statement in the User model is never executed.

If I change the ‘db’ entry in the app (not the test one) configuration to point to the test DB, the test succeeds, which makes me think that, somehow, during the test, the test configuration is not use as it should, but the main app configuration is used.

Any ideas?

(M Marsella) #2

OK, I found that the problem is that my index-test.php is not called. This is because the Apache configuration for pretty URLs routes requests to index.php. I would prefer not to change the Apache configuration when testing, so I merged index-test.php and index.php file as follows:

defined(‘YII_DEBUG’) or define(‘YII_DEBUG’, true);

defined(‘YII_ENV’) or define(‘YII_ENV’, ‘dev’); //TODO Set to test for testing

require(DIR . ‘/../vendor/autoload.php’);

require(DIR . ‘/../vendor/yiisoft/yii2/Yii.php’);


if (!in_array(@$_SERVER['REMOTE_ADDR'], ['', '::1'])) {

    die('You are not allowed to access this file.');


$config = require(__DIR__ . '/../tests/codeception/config/acceptance.php');

} else {

$config = require(__DIR__ . '/../config/web.php');


(new yii\web\Application($config))->run();

I just need to set YII_ENV to ‘test’, or ‘dev’ (or comment the line altogether) and it appears to be working fine. What do you think?