Is it possible to test an abort that was called inside a model?

Published 4 weeks ago by markandrewkato

Hi everyone,

I want to unit test my User Model if the assignRole method would throw an error if an invalid role name was entered. The method inside looks like this:

public function assignRole($role)
    {
        $role = Role::where('name', $role)->first();

        if (! $role) {
            abort(422, "Invalid role assigned");
        }

        $this->roles()->attach($role->id);
    }

It's working. I just don't know how to test it. Is this possible? If not, what's the best way to do this? Or am I doing something wrong here?

Any help would be appreciated. Thanks!

BishoyWagih

try something like this..

/** @test */

public function a_role_can_be_assigned_to_a_user()
{   
    $role = Role::where('name', 'test_role')->first();

    $this->assertInstanceOf('App\Role' , $role);

    $user = factory('App\User')->create();

            $user->roles()->attach($role->id);

    $this->assertDatabaseHas('role_user' , [$user->id , $role->id]);
}

where role_user is the pivot table between users and roles...

markandrewkato

Hi @BishoyWagih,

Thanks for the reply. I already have a test which checks if a valid role can be assigned to a user. What I want to do is to check if the assignRole method would throw an exception using the abort helper if an invalid role is entered.

Please sign in or create an account to participate in this conversation.