Skip to content

Instantly share code, notes, and snippets.

@walva
Created June 15, 2021 06:41
Show Gist options
  • Save walva/fa66e08a2d4c1f519295dbfd1934551b to your computer and use it in GitHub Desktop.
Save walva/fa66e08a2d4c1f519295dbfd1934551b to your computer and use it in GitHub Desktop.
DatabaseContext for behat
<?php
namespace App\Tests\Behat;
use Behat\Behat\Context\Context;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class DatabaseContext implements Context
{
private SchemaTool $schemaTool;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadata[]
*/
private array $classes;
public function __construct(
public EntityManagerInterface $entityManager,
protected $projectDir
)
{
$this->schemaTool = new SchemaTool($this->entityManager);
$this->classes = $entityManager->getMetadataFactory()->getAllMetadata();
}
/**
* @BeforeScenario @emptyDatabase
*/
public function emptyDatabase($event)
{
$this->schemaTool->dropSchema($this->classes);
$this->schemaTool->createSchema($this->classes);
}
/**
* @BeforeScenario @fixtures
*/
public function loadFixtures($event)
{
$env = 'test';
$groups = 'behat';
$command = [
"bin/console",
'doctrine:fixtures:load',
"--env={$env}",
"--group={$groups}",
"-n",
];
$process = new Process($command);
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
echo $process->getOutput();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment