Laravel 5.5.14 - PHPUnit 6 - Policy - Action Not Authorized

Issue

After upgrading to Laravel 5.5.14 from 5.4, I received errors on two tests that “This action is unauthorized”. Both tests were delete commands, and both employ the use of policies.

;TLDR

Make sure that you have a function named for the action you are authorizing against. In this case, I was calling:

$this->authorize('delete',$contactType);

did not have a “Delete” function created within the ContactType Policy.

Background

In this application, I am only allowing Site Administrators to remove the Contact Types. Therefore, in the “Before” function, I am checking if the user is a Site Administrator. If he is, the allow the action to occur. If he is NOT, then proceed to the actual method and review the authorization there:

public function before($user, $ability)
{
if (! $user->getSelectedRole()) {
return false;
}

if ($user->isSiteAdministrator()) {
return true;
}
}

did not have a “Delete” function created, as no other user type is allowed to perform this action…and if the function didn’t exist, it returned false. Cool.

Solution

In 5.5, I guess a change was made to check that the requested function exists first, then process the “before” method. I’m not 100% on this as the issue, but I simply corrected the error by creating a “delete” method within the policy:

/**
 * Determine whether the user can delete contact types.
 * @param\App\User $user
 * @return mixed
 */
public function delete(User $user)
{
return false;
}