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

时间:2019-01-27 18:30:42

标签: php laravel laravel-5.7 php-7.2 phpunit-testing

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

  

1)   Tests \ Feature \ FunderFeatureTest :: an_admin_should_be_able_to_view_a_list_of_funders   Symfony \ Component \ Debug \ Exception \ FatalThrowableError:太少   函数App \ Policies \ FunderPolicy :: view()的参数,传入了1   /home/vagrant/code/rtl/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php   在614行,正好是2个

我在做什么错?所有其他策略均有效(包括不需要模型的create()和store()方法)。我意识到这与SO上的许多其他问题类似,但是大多数问题似乎是由于人们没有将类名传递给authorize方法或问题发生在不同的控制器方法(例如update() )。我很抱歉,如果以前曾问过这个特定问题,我已经对这个问题进行了两个星期的研究,但找不到我想要的答案。

FundersController.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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

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