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

Conversation

Projects
None yet
2 participants
@arjanwestdorp
Contributor

arjanwestdorp commented May 16, 2018

Sometimes you want to fake the events for only a part of your test and not the whole test. For example to create some factories for models that rely heavily on events. We could need those events to be faked for that part, but not for the actual feature test we are performing.

In the example below the subscription would have some actions being performed through event listeners. For example a CreateUniqueNumberForSubscription and a CreateInvoiceForSubscription. When creating the factory subscription we don't want those events to be triggered, but when making a child subscription (the actual feature test) we want to dispatch all the events and test the result of those events being triggerd. For example by testing if the invoice was created correctly.

/** @test */
public function it_can_create_a_child_subscription() {
    $subscription = Event::fakeFor(function () {
        return factory(Subscription::class)->create();
    });

    $this->json('POST', '/subscriptions', [
        'parent_id' => $subscription->id,
    ])
        ->assertStatus(201);

    // assert this new created subscription has data filled by some event listener.
}

It would still have the possibility to only fake some events when passing those events to the second parameter:

Event::fakeFor(function () {
    return factory(Subscription::class)->create();
}, [OnlyThisEvent::class]);

And it also would still be possible to check if events are being dispatched on the EventFake inside of this fakeFor() callable:

Event::fakeFor(function () {
    return tap(
        factory(Subscription::class)->create(),
        function ($subscription) {
            Event::assertDispatched(OnlyThisEvent::class);
        }
    );
}, [OnlyThisEvent::class]);

@GrahamCampbell GrahamCampbell changed the title from Allow faking events for only a specific part to [5.6] Allow faking events for only a specific part May 16, 2018

@taylorotwell taylorotwell merged commit 09d3473 into laravel:5.6 May 18, 2018

2 checks passed

continuous-integration/styleci/pr The analysis has passed
Details
continuous-integration/travis-ci/pr The Travis CI build passed
Details
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment