I am strugling on how to mock permissions that I've setup according to the laracast ACL in Laravel: Roles and Permissions.
Since AuthServiceProvider@getPermissions does not return any permissions from the DB when running the tests, it's obvious that I can also not take the permissions into account when testing.
Hence, I'd like to mock the Gate Facade, however I have no idea how to do that and would be happy for some help.
For some context, see my AuthServiceProvider.php
<?php
namespace App\Providers;
use App\Permission;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Cache;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
// Dynamically register permissions with Laravel's Gate.
foreach ($this->getPermissions() as $permission) {
$gate->define($permission->name, function ($user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
protected function getPermissions()
{
// if running tests, this will be called before migrations are run, thus, there won't be a `permission` table and eloquent will throw and Exception
// catching the Exception to return an empty array of `permissions`in order for laravel to keep on booking when running tests
try {
return Cache::remember("auth.permissions", 10, function () {
return Permission::with('roles')->get();
});
} catch (\Exception $e) {
return [];
}
}
}