trafalgar
trafalgar

Reputation: 736

Can you test with a test database copy instead of Fixtures with CakePHP3?

I'm using CakePHP3 and have copied the production database (my_app) into a test database (test_my_app). The details of the test connection are listed in app.php and debug is set to true.

Do I need to use fixtures or will my controller tests pickup the test database? At the moment when I post to controller (REST API) it seems to apply to the production database, instead of the test db. The app is running on http://localhost/my_app/ which is the url used in the controller testing.

I'm running tests on the console with :

$ vendor/bin/phpunit tests/TestCase/Controller/ArticlesControllerTest

This is still in dev stages so the databases are small.

This is the code:

public function testAdd()
{
    $users = TableRegistry::get('Users');
    $query = $users->find('all');
    $before = $query->count();
    $params = [
        'username' => 'foo',
        'email' => '[email protected] ',
        'password' => 'password',
        'fullname' => 'Elbart Bart',
        'status' => 'active'
    ];
    $this->configRequest([
        'headers' => [
            'Authorization' => 'Bearer ' . $this->token
        ]
    ]);
    $this->post('users/add', $params);
    $query2 = $users->find('all');
    $after= $query2->count();
            debug($before);
    $this->assertEquals($after,$before+1);
}

Upvotes: 0

Views: 233

Answers (1)

trafalgar
trafalgar

Reputation: 736

Yes you can test using a test DB, you don't need fixtures at all. I copied the my_app database into test_my_app, and the CakePHP test conventions were able to pick it up.

Also make sure not to use the absolute/full URL as that then uses the production database -

// so DON'T do this 
$this->post('http://localhost/my_app/users/add', $data). 

//Instead do:
$this->post('/users/add', $data);

Upvotes: 1

Related Questions