Skip to content

Instantly share code, notes, and snippets.

@marijoo
Last active October 20, 2021 10:02
Show Gist options
  • Save marijoo/5f9ec32670c872ed5e8ea11d39a4a6e4 to your computer and use it in GitHub Desktop.
Save marijoo/5f9ec32670c872ed5e8ea11d39a4a6e4 to your computer and use it in GitHub Desktop.
This allows to assert against the Laravel Gate by providing a simple array with policy methods.
<?php
namespace Tests\Traits;
use App\User;
use Illuminate\Support\Facades\Gate;
use ReflectionMethod;
trait AssertsPolicy
{
protected function assertGateMethod(string $name, bool $accessible = true, ...$params): void
{
$assertion = $accessible ? 'assertTrue' : 'assertFalse';
if (!$params) {
$method = new ReflectionMethod(Gate::getPolicyFor($this->model), $name);
$params = [$this->model];
if ($method->getNumberOfParameters() === 2) {
$params[] = $this->model::factory()->create();
}
}
$this->{$assertion}(
Gate::check($name, $params)
);
}
protected function assertGateMethods(array $methods, bool $accessible): void
{
foreach ($methods as $name => $params) {
if (is_bool($params)) {
$this->assertGateMethod($name, $params);
continue;
}
if (!is_array($params)) {
$this->assertGateMethod($params, $accessible);
continue;
}
$this->assertGateMethod($name, $accessible, ...$params);
}
}
protected function assertUserCan(array $methods, ?User $user = null): void
{
if ($user) {
$this->actingAs($user);
}
$this->assertGateMethods($methods, true);
}
protected function assertUserCannot(array $methods, ?User $user = null): void
{
if ($user) {
$this->actingAs($user);
}
$this->assertGateMethods($methods, false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment