Cleaning up after each Test Run
As it stands we have our Behat test suite up and running. We've defined our basic GET
, POST
, PUT
, PATCH
, and DELETE
scenarios, and we've created a Background step to setup the database by dogfooding our own API.
I keep saying it, but it's worth repeating:
The way we are using Behat here is unusual.
We're trying to save ourselves the hassle of creating and maintaining multiple identical test suites. We will have a bunch of JSON API implementations that all follow the exact same spec. This is a non-typical circumstance.
As we've extracted and centralised our test suite, we hit on some unique challenges that typically would be trivial to solve.
Adding data is one.
Cleaning up after ourselves is another.
What I don't want to do is set up some weird /cleanup
endpoint, or something of that nature, and when hit this would truncate our database tables. Nasty.
Instead, I'm going to go hardcore and smash a SQL command in via PDO.
// features/bootstrap/FeatureContext.php
/**
* @BeforeScenario
*/
public function cleanUpDatabase()
{
$host = '0.0.0.0';
$db = 'basic_api';
$port = 3306;
$user = 'dbuser';
$pass = 'dbpassword';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
$pdo->query('TRUNCATE album');
}
Even if you don't understand how this works, the code itself should hopefully explain what's happening.
This is an awesome tutorial on PDO that tells you more about the topic than I ever could.
We're telling Behat that before any scenario (via the @BeforeScenario
annotation) to run this cleanUpDatabase
method.
This method uses the given parameters to directly connect to our database server / container.
Once connected all we are doing is a TRUNCATE
which deletes all the data in the album
table, and crucially resets the auto incrementing ID field back to 0.
This will be important for our GET
tests, which will expect to start at ID 1.
Hardcode Mode
The downside to this approach is that when we switch projects we will need to swap out our configuration. This should be as simple as updating the variables, or changing the $dsn
to connect to Postgres.
This may seem a bit nasty to you.
I'm open to suggestions on a better implementation given the limitations described in sharing the test suite.
I appreciate at this point in the course we haven't even got to setting up and configuring a database. So let's get on to that very topic in the next video.