I am working with an application built on Laravel 11. I have a Survey model with the following public function:
public function finish(): void
{
$this->update([
'finished_at' => Carbon::now(),
]);
event(new SurveyFinishedEvent($this));
}
The SurveyFinishedEvents triggers a listener that makes API calls. When running unit tests, I would rather not go to the effort of setting up the API mocking in every test that involves calling this function so I am trying to suppress events. Here is an example:
/**
* @covers finish
*/
public function test_finish_whenEventsSuppressed_thenNoEventsDispatched(): void
{
// Arrange.
$survey = Survey::factory()->create();
Event::fake();
// Act.
Survey::withoutEvents(function () use ($survey) {
$survey->finish();
});
// Assert.
Event::assertNotDispatched(SurveyFinishedEvent::class);
}
This fails. withoutEvents is failing to prevent the dispatch of the SurveyFinishedEvent. Am I misunderstanding the purpose of withoutEvents?
I have considered registering the event on the model via the $dispatchesEvents variable, but I do not want the event to be triggered every time the survey is updated, only when the finished_at date is updated.