php - 传递类名以查看控制器索引方法上的策略返回错误,即传递的参数太少
问题描述
我正在尝试测试我的控制器的索引方法的策略。我将类名传递给授权助手,但我收到 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);
}
}
解决方案
我不确定这是否是让它工作的适当方法,但传递一个 Funder 模型的新实例而不是类名似乎可以解决问题。
更改$this->authorize('view', Funder::class);
为$this->authorize('view', new \App\Funder());
推荐阅读
- visual-studio - 从发布模式和调试模式生成的 .pdb 文件有什么区别?
- c++ - 使用 windows API 将注册表文件导入注册表
- python - 如何在多 GPU 自定义 GAN 中停止此错误?
- html - 如何删除图像边框上的空白 - CSS
- ruby-on-rails - Rails 迭代一个集合并返回它
- unicode - 阿拉伯文字显示奇怪的字符 الÙباى انگليسى ØŒ
- python - Download file from a django UpdateView template
- qt - 在 QML 中定义和组合自定义元素的正确方法
- c# - 在 asp.net core 3 MVC 中包含列表属性的模型的表单
- php - 从刀片传递道具到vue组件时出现意外的令牌'{'