Skip to content

Instantly share code, notes, and snippets.

@jakzal
Last active September 16, 2018 07:22
Show Gist options
  • Save jakzal/1408840 to your computer and use it in GitHub Desktop.
Save jakzal/1408840 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');
}
}
@marijn
Copy link

marijn commented Nov 30, 2011

Nice! Why not add it to CommonContext?

@jakzal
Copy link
Author

jakzal commented Nov 30, 2011

That's what I'm planning to do. @everzet already pointed this out :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment