After figuring out the way to load the sql fixtures
it was time to integrate fixtures loading in our behat suites.
While I’ll keep my thoughts on behat for another time, with just a bit
of googling you can find a lot of material how to load fixtures before scenario/feature, for example Robert’s post, or you could use Alice behat extension, or if you like plain and simple,
you could use Behat Fixtures extension.
This way or that, you have a lot of options, still, they require more or less
work to get up and running, and in our particular case, there was a problem
of sql inserts.
Latelly I have been trying to hold to “law of parsimony” to make
the simplest solution possible, and complicate it only when needed.
With that in mind, it occured to me, that I could circumvent a nice chunk of code
by executing the doctrine:fixtures:load with arguments before running
behat feature.
All the pieces were there, just needed to connect them in a meaningfull way.
I would need to use Symfony Process component to execute
the shell command we need.
<?phpnamespaceAppBundle\Tests\Features\Context;
useBehat\WebApiExtension\Context\WebApiContext;
usePHPUnit\Framework\Assert;
useSymfony\Component\Process\Exception\ProcessFailedException;
useSymfony\Component\Process\Process;
classBaseContextextendsWebApiContext
{
/**
* Load data fixtures by executing the console command
*
* @param $fixture The directory to load data fixtures from
* @param $em The entity manager to use for this command
* @param $env The environment name
*/publicstaticfunctionloadDataFixture($fixture, $em, $env):void
{
print(__DIR__) .PHP_EOL;
$command =__DIR__."/../../../../../bin/console doctrine:fixtures:load --env={$env} --fixtures={$fixture} --em={$em} -n";
$process =newProcess($command);
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
thrownewProcessFailedException($process);
}
echo $process->getOutput();
}
}
The code is pretty much standard and no surprises there, apart from the
atrocity of line 22, but hey, it works.
It is a bit generalized so you can pass the path to fixtures, entity manager, and environment name.
Awesome, now how to use it?
Well, after looking into behat hooks, I learned that I need
to hook into the BeforeFeature, by annotating a static function with it