Skip to content

Instantly share code, notes, and snippets.

@ronisaha
Forked from jakzal/FeatureContext.php
Created September 16, 2018 07:22
Show Gist options
  • Save ronisaha/7a5b4d16ce31e0aebb007807883c364d to your computer and use it in GitHub Desktop.
Save ronisaha/7a5b4d16ce31e0aebb007807883c364d to your computer and use it in GitHub Desktop.
Generating schema before Behat scenarios in Symfony2
<?php
namespace Behat\CommonContext;
use Behat\BehatBundle\Context\BehatContext;
use Behat\Behat\Event\ScenarioEvent;
use Doctrine\ORM\Tools\SchemaTool;
/**
* Provides hooks for building and cleaning up a database schema with Doctrine.
*
* While building the schema it takes all the entity metadata known to Doctrine.
*
* @author Jakub Zalas <jakub@zalas.pl>
* @license MIT
*/
class SymfonyDoctrineContext extends BehatContext
{
/**
* @param \Behat\Behat\Event\ScenarioEvent $event
*
* @BeforeScenario
*
* @return null
*/
public function beforeScenario(ScenarioEvent $event)
{
$this->buildSchema();
}
/**
* @param \Behat\Behat\Event\ScenarioEvent $event
*
* @AfterScenario
*
* @return null
*/
public function afterScenario(ScenarioEvent $event)
{
$this->getEntityManager()->clear();
}
/**
* @return null
*/
protected function buildSchema()
{
$metadata = $this->getMetadata();
if (!empty($metadata)) {
$tool = new SchemaTool($this->getEntityManager());
$tool->dropSchema($metadata);
$tool->createSchema($metadata);
}
}
/**
* @return array
*/
protected function getMetadata()
{
return $this->getEntityManager()->getMetadataFactory()->getAllMetadata();
}
/**
* @return \Doctrine\ORM\EntityManager
*/
protected function getEntityManager()
{
return $this->getContainer()->get('doctrine.orm.entity_manager');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment