Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel testing: model factory doesn't trigger Registered event

I’ve used Laravel 5.7 for quite some time now, however, I am totally new to TDD.

If a user model is created, a register event is getting triggered. But why isn't it fired when I am creating the user model with a factory?

My factory:

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'first_name' => $faker->name,
        'sur_name' => $faker->name,
        'phone' => $faker->phoneNumber,
        'birthday' => Carbon::now()->subYears(25)->toDateTimeString(),
        'gender' => 'm',
        'email' => $faker->unique()->safeEmail,
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

and my Test, which fails:

public function test()
{

    $this->withoutExceptionHandling();

    Event::fake();
    $user = factory(User::class)->create();

    Event::assertDispatched(Registered::class);

}
like image 990
Patrick Schocke Avatar asked Dec 29 '25 03:12

Patrick Schocke


1 Answers

The Registered event is dispatched by the controller when using the auth scaffolding provided by Laravel (specifically, the register() method in the Illuminate\Foundation\Auth\RegistersUsers trait. Since you're not making a request through the controller, it doesn't dispatch the event.

like image 54
Travis Britz Avatar answered Jan 01 '26 17:01

Travis Britz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!