Search code examples
laravellaravel-testinglaravel-events

Laravel unit testing if an event is triggered when an eloquent model event is triggered


I am developing a Laravel application and writing tests as I go along the way. Now, I am having a problem writing a test that is asserting if an event is triggered when an eloquent model event is triggered. This is what I am doing.

This is my ItemObserver's created function

public function created(Item $item)
{
    event(new NewItemCreated($item));
}

As you can see I am firing an event inside the created event of the eloquent model observer.

If I want to assert if an event is triggered in the test, I have to fake the event and then assert something like this.

Event::fake();
factory(Item::class)->create(); //created function of observer should be triggered but it will not be
Event::assertDispatched(NewItemCreated::class);

As you can see in the test code I am trying to assert that if an event is triggered when an item is created. But the test will never pass because the created function of the observer class is never called because the Event is faked in the test. How can I test this scenario?


Solution

  • Only fake the event you want to test:

    Event::fake([NewItemCreated::class]);
    

    Relevant documentation.