eloquent-uuid icon indicating copy to clipboard operation
eloquent-uuid copied to clipboard

Boot events break with Event::fake() when testing

Open rask opened this issue 7 years ago • 4 comments

I'm trying to test event dispatching in my application using the PHPUnit tools provided by Laravel.

In a test where Event::fake() is called before creating a new Model (a User for instance) the package's UUID trait's boot method seems to break.

I get MySQL errors relating to field id not having a default value:

QueryException: SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into ...

I'm using Laravel 5.6 as my application base.

Trimmed example code to reproduce:

<?php

class migration_dis_and_dat
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->uuid('id');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamps();

            $table->primary('id');
        });
    }
}
<?php

class User extends Model {
    use UuidModelTrait;

    ...
}
<?php

class UserTest extends TestCase
{
    public function test_user_create_dispatches_event()
    {
        Event::fake();

        User::create(['email' => '[email protected]', 'password' => Hash::make('helloworld'));

        // around here the error should appear,
        // if you comment `Event::fake()` and `Event::assertDispatched`
        // then the user should be created normally

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

rask avatar Mar 07 '18 22:03 rask

Have you tried setting the id by using the Faker library?

JValck avatar Mar 18 '18 14:03 JValck

The ID is not fillable but I think I could try that for the sake of testability of the events themselves.

rask avatar Mar 18 '18 21:03 rask

Also try to report this to laravel/framework project, you may get some feedback whether this is an issue with the framework or if there are any clean solutions to it.

See also: https://github.com/laravel/framework/issues/18066

vpratfr avatar Jul 03 '18 15:07 vpratfr

This has been fixed in https://github.com/laravel/framework/pull/25185 which has been released in 5.6.34.

X-Coder264 avatar Sep 01 '18 13:09 X-Coder264