5

I'm using the package spatie/laravel-sluggable in my project. I need to assert that an event was dispatched. The problem is when I fake the event (Event::fake([AdvertPublished::class])) in the test, in theory only my Advertpublished event should be faked, but it seems the pacakge events are also faked and the method that creates the slug generateSlugOnCreate is never executed what results in a sql error because my slug field can't be null.

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

$response = $this->json('POST', '/company/adverts', ['foo' => 'bar'])
    ->assertStatus(201);

$advert = Advert::first();
Event::assertDispatched(AdvertPublished::class, function ($e) use ($advert) {
    return $e->advert->id === $advert->id;
});

Some one knows if I'm missing something or what can be the problem?

Jairo
  • 131
  • 1
  • 11
  • This looks more like an integration test than a unit test to me, I don't normally fake events in integration testing. – Devon Bessemer Jul 23 '18 at 17:21
  • The code looks right, I've never tried to fake just one event, but it looks like you've passed it correctly after reviewing the event facade and the eventfake class. – Devon Bessemer Jul 23 '18 at 17:27
  • 1
    I know, it's crazy! I'm stuck with no idea about why the Eloquent events are faking too – Jairo Jul 23 '18 at 17:52
  • Are you overriding setup or anything that would prevent the app container from being refreshed from another test? – Devon Bessemer Jul 23 '18 at 18:13
  • I would test this separately, I would test that such and such event was fired and in separate test just test the function `generateSlugOnCreate(..)`. And if I want to be sure even more I hit controller and assert database changes... – Kyslik Jul 23 '18 at 20:02
  • @Devon, I override the setUp method, but I ensure to call `parent::setUp()` to call the original method. However even if I comment my override setUp method, the things still don't work. – Jairo Jul 23 '18 at 20:31
  • @Kyslik, that's exactly what I'm trying to do, I'm just interested in assert that the event is fired, **but** other events are also faked, thing that shouldn't be like that beacause I'm specifying `Event::fake([AdvertPublished::class])` – Jairo Jul 23 '18 at 20:35
  • I dont use fakes provided by Laravel; open up code and see what that static call does; if I need to fake an event I swap/bind/alias it in `setUp` with the fake one; same for mails and other fakes. – Kyslik Jul 23 '18 at 21:46

0 Answers0