Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Allow faking events for only a specific part #24230

Merged
merged 4 commits into from
May 18, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Illuminate/Support/Facades/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,26 @@ public static function fake($eventsToFake = [])
Model::setEventDispatcher($fake);
}

/**
* Replace the bound instance with a fake for the given callable only.
*
* @param callable $callable
* @param array|string $eventsToFake
* @return callable
*/
public static function fakeFor(callable $callable, array $eventsToFake = [])
{
$initialDispatcher = static::getFacadeRoot();

static::fake($eventsToFake);

return tap($callable(), function () use ($initialDispatcher) {
Model::setEventDispatcher($initialDispatcher);

static::swap($initialDispatcher);
});
}

/**
* Get the registered name of the component.
*
Expand Down
66 changes: 66 additions & 0 deletions tests/Support/SupportFacadesEventTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Illuminate\Tests\Support;

use Mockery;
use PHPUnit\Framework\TestCase;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Facade;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Testing\Fakes\EventFake;

class SupportFacadesEventTest extends TestCase
{
protected function setUp()
{
parent::setUp();

$this->events = Mockery::spy(Dispatcher::class);

$container = new Container;
$container->instance('events', $this->events);

Facade::setFacadeApplication($container);
}

public function tearDown()
{
Event::clearResolvedInstances();

Mockery::close();
}

public function testFakeFor()
{
Event::fakeFor(function () {
(new FakeForStub())->dispatch();

Event::assertDispatched(EventStub::class);
});

$this->events->shouldReceive('dispatch')->once();

(new FakeForStub())->dispatch();
}

public function testFakeForSwapsDispatchers()
{
Event::fakeFor(function () {
$this->assertInstanceOf(EventFake::class, Event::getFacadeRoot());
$this->assertInstanceOf(EventFake::class, Model::getEventDispatcher());
});

$this->assertSame($this->events, Event::getFacadeRoot());
$this->assertSame($this->events, Model::getEventDispatcher());
}
}

class FakeForStub
{
public function dispatch()
{
Event::dispatch(EventStub::class);
}
}