Ad

Does Laravel 6 Disable Observers In Factories / Tests?

- 1 answer

Ive just written an observer thats sends an e-mail whenever a user is created.

class UserObserver
{
    public function created(User $user)
    {
         Mail::to($user)->send(new UserAccountCreated(
            app('auth.password.broker')->createToken($user),
            $user
        ));
    }
}

I ran phpunit to test if my observer works, and it passed. However I was expecting to get an email for each time my tests create a user.

For example:

/** @test */
    public function an_admin_can_view_all_clients()
    {
        $user = factory(User::class)->create(['is_admin' => true]);
        $client = factory(Client::class)->create();
        $client2 = factory(Client::class)->create();

        $this->actingAs($user)->get(route('clients.index'))
            ->assertSuccessful()
            ->assertSee($client->name)
            ->assertSee($client2->name);
    }

I would expect an email to be sent when that factory creates the user. But I don't receive one in Mailtrap.

Just wondering if and where laravel disables my observer being triggered when my factory creates that user.

Ad

Answer

No you have to disable it yourself by using Model::withoutEvents()

For example:

$user = User::first();
User::withoutEvents(function () use ($user) {
    $user->delete();
});

Also in this specific case you can also use the Mail fake system provided by Laravel itself

Ad
source: stackoverflow.com
Ad