symfonydoctrine-ormdoctrinenelmio-alicealice-fixtures

Take fixture item by reference in nelmio-alice


I have a set of fixtures (here is a simplification):

My\Entity\User:
  user_{1..10}:
    name: <firstName()>

My\Entity\Item:
  item_{1..10}:
    user: '@user_$current'
    data: <numberBetween(111111111, 999999999)>

I want to fetch Item with ID 4 inside my phpunit functional test.

I can't be sure that autoincrement ID is started from 1. It's not 1 after TRUNCATE. So this is incorrect:

$item4 = $this->em->getRepository(Item::class)->find(4);

How can I get a reference to item_4?


Solution

  • You can get the entities generated from the fixtures file directly from the loader:

    $loader = new Nelmio\Alice\Loader\NativeLoader();
    $objectSet = $loader->loadFile(__DIR__.'/fixtures.yml');
    

    The $objectSet should contain all your entities by their alias, so you can get a specific item and directly work with it or fetch it again using your repository

    $fixtureItem4 = $objectSet['item_4'];
    $persistedItem4 = $this->em->getRepository(Item::class)->find($fixtureItem4->getId());