thephpleague / factory-muffin

Enables the rapid creation of objects for testing
https://factory-muffin.thephpleague.com/
MIT License
531 stars 72 forks source link

Model Observers #344

Closed olsgreen closed 9 years ago

olsgreen commented 9 years ago

I've just spent the last two hours trying to track down why some files created by a Factory Muffin generated model instance haven't been being cleared via the registered observer.

My observers are registered in the relevant models boot method is like so:

public static function boot()
{
    parent::boot();
    Image::observe(new ImageObserver);
}

In my tests I have standard calls to the factory to generate Images:

public function testGetExistingImageByOrder()
{
    $image1 = Facade::create('My\Name\Space\Image\Image', array('order' => 0));
    $image2 = Facade::create('My\Name\Space\Image\Image', array('order' => 1));
    $this->assertTrue($image1->delete());
    $this->assertTrue($image2->delete());
}

In the model observer deleting method I try and perform some cleanup, then return a boolean response.

If I run the tests separately the deleting events are dispatched fine by Laravel and my observers perform their tasks. However, if I run the tests in succession, the events are dispatched to the first instance of the model but not subsequent instances in the following tests.

It appears that the binding is lost between the model and observer somewhere between the tests. I've had a look at the Eloquent model code, and in specific the bootIfNotBooted() method. I'm assuming that the static registry used to keep track of whether the model has been booted is in conflict with either PHPUnit or Factory Muffin ripping apart the class after each test?

A workaround that I've found to work is to just rebind the observer by overloading phpUnits setUp() method.

Any ideas? Am I missing something? I realise this may be a problem with the Laravel and phpUnit interaction, thought I would post here first anyway through.

Cheers,

Oliver

GrahamCampbell commented 9 years ago

Thanks, but this definitely isn't an issue with factory muffin. We do nothing special or hacky with eloquent, and don't do anything at all with the booting. All we do is call save and delete on the models, nothing more.

olsgreen commented 9 years ago

I did think as much, thanks anyway.

GrahamCampbell commented 9 years ago

No problem. :)