Time to put the WPDb module under test.
Not that much use
The WPDb module is one of the less used ones among the modules wp-browser provides.
I am the first one that’s using the WP Loader module 99% of the time but a recent use case requiring database access during acceptance tests revealed an underlying issue.
While I’m at it and am not in a terrible rush I will refactor the class and TDD it while doing so. The module provides methods meant to be used in functional and acceptance tests and it can really make the interaction with WP database easier when having to insert posts, users, comments or meta.
Setup
To test the class I’ve overhauled the old tests and will use the same drill over and over:
- set up needed pre-conditions using known and tested methods from the
Db
module - execute
WPDb
specific methods - verify the output using
Db
module
The set up is a fairly standard Codeception one:
# Codeception Test Suite Configuration
# suite for functional (integration) tests.
# emulate web requests and make application process them.
# Include one of framework modules (Symfony2, Yii2, Laravel4) to use it.
class_name: FunctionalTester
modules:
enabled:
- FunctionalHelper
- WPDb
config:
WPDb:
url: 'http://eeeeeeeeee.local'
dsn: 'mysql:host=127.0.0.1;dbname=codeception-tests'
user: 'root'
password: 'root'
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
checkExistence: true
update: true
Where I’m using the WPDb
module itself as a method supplier.
Have a user in the database
I’ve simply pulled up the first method supplied by the WPDb
module and generated a new test case
codecept generate:cest WPDbUser
And will write the first test to verify expectations
<?php
class WPDbUserCest
{
public function _before(FunctionalTester $I)
{
}
public function _after(FunctionalTester $I)
{
}
/**
* @test
* it should insert a user in the database
*/
public function it_should_insert_a_user_in_the_database(FunctionalTester $I)
{
$I->wantTo('insert a user in the database and see generated defaults');
$I->haveUserInDatabase('Luca');
$table = 'wp_users';
$criteria = ['user_login' => 'luca',
'user_pass' => 'luca',
'user_nicename' => 'Luca',
'user_email' => 'luca@example.com',
'user_url' => 'http://luca.example.com',
'user_status' => 0,
'user_activation_key' => '',
'display_name' => 'Luca',
];
foreach ($criteria as $key => $value) {
$I->seeInDatabase($table, [$key => $value]);
}
}
}
Next
I will write more tests and give the module back the love and consideration it deserves.