Search code examples
symfonydoctrine-ormbehat

Creating Doctrine objects from a Behat Context class


Situation

I have a Symfony2 project. I want to create Doctrine objects during a Behat test. To that effect, I need to access the EntityManager from within my FeatureContext class.

My attempt

I have my FeatureContext class extend RawMinkContext, which in turn extends BehatContext.

I then try, as per the documentation to access the container, or the entitymanager.

class FeatureContext extends RawMinkContext
{
    /**
     * @Given /^I have some disciplines$/
     */
    public function iHaveSomeDisciplines()
    {
        $em = $this->getEntityManager();
        $container = $this->getContainer();
    }

But neither of these work, because none of the classes FeatureContext inherits from have access to this. As far as I know, only Controller does.

Question

How can I get access to Doctrine from within my FooContext classes?


Solution

  • Inject the kernel into your context by:

    Behat2

    class FeatureContext extends RawMinkContext implements KernelAwareContext
    

    Behat3

    class FeatureContext extends RawMinkContext
    {
        use KernelDictionary
    

    Then you can get the entity manager as follows:

    $this->getKernel()->getContainer()->get('doctrine.orm.entity_manager');