首页 > 解决方案 > 传递类名以查看控制器索引方法上的策略返回错误,即传递的参数太少

问题描述

我正在尝试测试我的控制器的索引方法的策略。我将类名传递给授权助手,但我收到 500 状态和错误提示

1) Tests\Feature\FunderFeatureTest::an_admin_should_be_able_to_view_a_list_of_funders Symfony\Component\Debug\Exception\FatalThrowableError: Too little arguments to function App\Policies\FunderPolicy::view(), 1 pass in /home/vagrant/code/rtl/vendor/ laravel/framework/src/Illuminate/Auth/Access/Gate.php 在第 614 行,预计正好 2

我究竟做错了什么?所有其他策略都有效(包括不需要模型的 create() 和 store() 方法)。我意识到这与 SO 上的许多其他问题类似,但大多数似乎是由于人们没有将类名传递给授权方法或问题发生在不同的控制器方法上(例如 update() )。如果之前有人问过这个具体问题,我深表歉意,我已经研究了两周,但找不到我正在寻找的答案。

资助者控制器.php

namespace App\Http\Controllers;

use App\Funder;
use Illuminate\Http\Request;

class FundersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $this->authorize('view', Funder::class);

        return view('funders.index', [
            'funders' => Funder::all(),
        ]);
    }
}

FunderPolicy.php

namespace App\Policies;

use App\User;
use App\Funder;
use Illuminate\Auth\Access\HandlesAuthorization;

class FunderPolicy
{
    use HandlesAuthorization;
    public function view(User $user, Funder $funder)
    {
        return ($user->isAdmin() || $user->isSuperAdmin());
    }
}

FunderFeatureTest.php(供参考)

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class FunderFeatureTest extends TestCase
{
    use RefreshDatabase;
    /** @test */
    public function an_admin_should_be_able_to_view_a_list_of_funders()
    {
        $this->withoutExceptionHandling();
        $this->signIn('admin');

        $this->get('/funders')
            ->assertOk();
    }

    /** @test */
     public function a_user_should_not_be_able_to_view_a_list_of_funders()
    {
        $this->signIn();

        $this->get('/funders')
            ->assertStatus(403);
    }
}

标签: phplaravellaravel-5.7php-7.2phpunit

解决方案


我不确定这是否是让它工作的适当方法,但传递一个 Funder 模型的新实例而不是类名似乎可以解决问题。

更改$this->authorize('view', Funder::class);$this->authorize('view', new \App\Funder());


推荐阅读