Skip to content

Instantly share code, notes, and snippets.

@tPl0ch
Created August 9, 2012 15:37
Show Gist options
  • Save tPl0ch/3305223 to your computer and use it in GitHub Desktop.
Save tPl0ch/3305223 to your computer and use it in GitHub Desktop.
FixtureTestCase
<?php
namespace Reizwerk\TestSuiteBundle\Test;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\Common\DataFixtures\Executor\MongoDBExecutor;
use Doctrine\Common\DataFixtures\Purger\MongoDBPurger;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* This TestCase enables to load fixtures automagically if you pass an array of
* bundles. Depends on the DoctrineDataFixturesBundle.
*/
abstract class FixtureTestCase extends WebTestCase
{
/**
* Add the Bundlenames from which to load the fixture
*
* @var array
* @staticvar
*/
public static $fixtures = array();
/**
* Holds the document manager instance
*
* @var Doctrine\ODM\MongoDB\DocumentManager
* @staticvar
*/
public static $dm;
/**
* Autoloads the fixtures passed in the static array $fixtures
*
* @param array $options The options to pass to `WebTestCase::createKernel()`
*
* @throws \InvalidArgumentException
*/
protected static function loadFixtures(array $options = array())
{
static::$kernel = static::createKernel($options);
static::$kernel->boot();
static::$dm = static::$kernel->getContainer()
->get('doctrine.odm.mongodb.document_manager');
$paths = array();
foreach (static::$fixtures as $bundle) {
$bundle = static::$kernel->getBundle($bundle, true);
if (!$bundle) {
continue;
}
$paths[] = $bundle->getPath().'/DataFixtures/MongoDB';
}
$loader = new ContainerAwareLoader(static::$kernel->getContainer());
foreach ($paths as $path) {
if (is_dir($path)) {
$loader->loadFromDirectory($path);
}
}
$fixtures = $loader->getFixtures();
if (!$fixtures) {
throw new \InvalidArgumentException(
sprintf('Could not find any fixtures to load in: %s', "\n\n- ".implode("\n- ", $paths))
);
}
$purger = new MongoDBPurger(static::$dm);
$executor = new MongoDBExecutor(static::$dm, $purger);
$executor->execute($fixtures, false);
}
/**
* Purges the db and shuts down the kernel
*/
protected function tearDown()
{
$purger = new MongoDBPurger(static::$dm);
$purger->purge();
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment