mercredi 27 mars 2019

How to mock a many-to-many relationship in Laravel unit tests

I have the following tables, users, roles and role_user which creates the many-to-many relationship.

In my UserFactory when creating users I assign them the basic role of 'user' like so:

$factory->afterCreating(User::class, function ($user, $faker){
    $roles = Role::where('name', 'user')->get();
    $user->roles()->sync($roles->pluck('id')->toArray());
});

And then in my unit test I can test for users that they are redirected with a 302 when trying to access admin pages:

$this->actingAs(factory(\App\User::class)->make());

$request = Request::create('/admin', 'GET');

$middleware = new AccessAdmin;
$response = $middleware->handle($request, function () {});

$this->assertEquals($response->getStatusCode(), 302);

This works as expected but the problem is testing the reverse of this with an admin user as I'm unsure how to mock the relational data. I have tried creating the user and then attaching the roles like so:

$user = factory(\App\User::class)->make();
$roles = Role::where('name', 'admin')->get();
$user->roles()->sync($roles->pluck('id')->toArray());

This gives me the following error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null

This is correct because the user is never created in the DB so the user has no ID.

How do I mock the user/role relationship?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire