jehad's avatar
Level 16

Model event not firing during Codeception test

I have a simple functional test for a registration using the L4 module, everything works except my newly added feature of automatically creating the username from the email address. Basically in my User model I have this:

    public static function boot()
    {
        parent::boot();

        // Automatically generate the user's username from their email address
        static::creating(function($user)
        {
            $user->username = preg_replace("/(@.+)|[^A-Za-z0-9]/", "", $user->email);
        });
    }

This works just fine in the browser, but in my test I get an error:

1) Failed to register a new account in Users/RegisterCept 

Couldn't click "Create Account":
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 users.username may not be NULL (SQL: insert into "users" ("first_name", "last_name", "email", "password", "updated_at", "created_at") values (John, Doe, john.doe@example.com, y$McoL9XKY8SHBaxoDAhMa0OjMdLYzHUW5O3rsPp0q.C5Wd2qew5M/W, 2014-10-01 20:23:48, 2014-10-01 20:23:48))

It's as if the creating() event isn't being fired.

Any ideas?

0 likes
4 replies
RayRutjes's avatar
Level 4

Maybe you could just change your implementation by creating an accessor instead of hooking into the model's lifecycle.

public function getUsernameAttribute($value)
{
    return ! $value ? preg_replace("/(@.+)|[^A-Za-z0-9]/", "", $this->email) : $value;
}
jehad's avatar
Level 16

@RayRutjes I thought about that but I'm using the username for routing as well ( users/@{username}).

Plus, this really should pass using a functional test. It's really weird.

RayRutjes's avatar

I don't see how my solution would break your routing logic, could you explain ?

jehad's avatar
Level 16

It wouldn't. I shouldn't be allowed to post of forums until I've had my coffee. I'll switch to using an accessor.

Even though this is still weird and would be great if someone came up with a solution, it's funny how TDD forces you to consider even the smallest aspect of your codebase.

I'm marking your reply as answer because it lets me go on with my life :)

Thanks!

Please or to participate in this conversation.