diff --git a/src/Illuminate/Support/Facades/Event.php b/src/Illuminate/Support/Facades/Event.php index cb4107fc54ee..02f26f95d9bf 100755 --- a/src/Illuminate/Support/Facades/Event.php +++ b/src/Illuminate/Support/Facades/Event.php @@ -45,6 +45,21 @@ public static function fake($eventsToFake = []) return $fake; } + /** + * Replace the bound instance with a fake that fakes all events except the given events. + * + * @param string[]|string $eventsToAllow + * @return \Illuminate\Support\Testing\Fakes\EventFake + */ + public static function fakeExcept($eventsToAllow) + { + return static::fake([ + function ($eventName) use ($eventsToAllow) { + return ! in_array($eventName, (array) $eventsToAllow); + }, + ]); + } + /** * Replace the bound instance with a fake during the given callable's execution. * @@ -66,6 +81,27 @@ public static function fakeFor(callable $callable, array $eventsToFake = []) }); } + /** + * Replace the bound instance with a fake during the given callable's execution. + * + * @param callable $callable + * @param array $eventsToAllow + * @return mixed + */ + public static function fakeExceptFor(callable $callable, array $eventsToAllow = []) + { + $originalDispatcher = static::getFacadeRoot(); + + static::fakeExcept($eventsToAllow); + + return tap($callable(), function () use ($originalDispatcher) { + static::swap($originalDispatcher); + + Model::setEventDispatcher($originalDispatcher); + Cache::refreshEventDispatcher(); + }); + } + /** * Get the registered name of the component. * diff --git a/tests/Integration/Events/EventFakeTest.php b/tests/Integration/Events/EventFakeTest.php index 3f5fab368aba..e6b7ab33c308 100644 --- a/tests/Integration/Events/EventFakeTest.php +++ b/tests/Integration/Events/EventFakeTest.php @@ -98,6 +98,29 @@ public function testNonFakedHaltedEventGetsProperlyDispatchedAndReturnsResponse( Event::assertNotDispatched(NonImportantEvent::class); } + public function testFakeExceptAllowsGivenEventToBeDispatched() + { + Event::fakeExcept(NonImportantEvent::class); + + Event::dispatch(NonImportantEvent::class); + + Event::assertNotDispatched(NonImportantEvent::class); + } + + public function testFakeExceptAllowsGivenEventsToBeDispatched() + { + Event::fakeExcept([ + NonImportantEvent::class, + 'non-fake-event', + ]); + + Event::dispatch(NonImportantEvent::class); + Event::dispatch('non-fake-event'); + + Event::assertNotDispatched(NonImportantEvent::class); + Event::assertNotDispatched('non-fake-event'); + } + public function testAssertListening() { Event::fake();