4

The app I am working on fires an event, when one of the Eloquent model attributes is updated.

The Eloquent model is called Job and it is supposed to fire JobCustomerTotalAmountDueChanged when the duration attribute is updated. I have the following code in the JobObserver:

public function saved(Job $job)
{
    if ($job->isDirty('duration')) {
        event(new JobCustomerTotalAmountDueChanged($job));
    }
}

When I try to test it using Event::fake, Eloquent events are not being fired, which means that the code in saved method is never execured. From what I see the assertDispatched and assertNotDispatched methods are only available for faked events. Is there a way to assert that a particular event is/is not fired without Event::fake?

Amade
  • 3,665
  • 2
  • 26
  • 54

1 Answers1

15

The solution turned out to be very easy after all:

Laravel lets you specify which events should be faked, as an argument to fake method. In my example:

Event::fake([JobCustomerTotalAmountDueChanged::class])

All of the other events are being triggered and handled. Also, you can make assertions only with reference to events passed as argument to fake method. If you don't pass any argument, Laravel will try to 'fake' every event in the app.

Amade
  • 3,665
  • 2
  • 26
  • 54
  • Amade, I'm trying to pass in the argument my specific event, have you any idea about why even doing this the model events are not being fired? I'm using spatie/laravel-sluggable package, and the slug is not being generated beacause the creating method is not being fired, what results in an mysql error for me because the slug field can't be null. – Jairo Jul 19 '18 at 22:36
  • This was added in Laravel 5.5. Which version are you using? – Amade Jul 20 '18 at 02:33
  • I'm using 5.6.26, so in theory should work. I'm stuck whit this – Jairo Jul 20 '18 at 21:29
  • Maybe you're calling Event::fake() without arguments somewhere? Also, you're not faking eloquent events, right? – Amade Jul 22 '18 at 02:13
  • I just check, I'm not calling Event::fake() without arguments anywhere else. And no, I'm just trying to fake my custom event. – Jairo Jul 23 '18 at 17:09
  • 1
    I think I just ran into the same issue as you. Looks like Eloquent events are not being fired. There is a workaround for it though. Check out the last answer (from November 2017) here: https://github.com/laravel/framework/issues/18066 – Amade Jul 29 '18 at 19:49
  • Thanks Amade, I'll use this hacky solution for now. – Jairo Aug 01 '18 at 21:52