Test event inside an Eloquent observer
Most times you test that events are fired by adding Event::fake()
to your tests. This will make Event::assertDispatched(SomeEvent::class)
to return true.
However, no events will trigger as soon as your specify Event::fake()
, no observers will be triggered to.
Event::fake()
takes an optional argument as an array to specify which event you want to look form. That means that you for example can let other events fire and only fire the one you want to test.
// UserObserver.php
class UserObserver
{
public function updated(User $user)
{
event(new SomeEventWhenUserChanged($site));
}
}
// UserEventTest.php
Event::fake([SomeEventWhenUserChanged::class]);
//...
$user->name = 'New name';
// This will trigger the UserObserver
$user->save();
Event::assertDispatched(SomeEventWhenUserChanged::class);