大家好,我想为控制器及其所有视图设计一个测试。
所有通往路线的视图都是安全的,这意味着用户必须先登录。
但不知怎么的,我没有更进一步。到目前为止我尝试过的:
$this->actingAs($user)->get('/excel'); // status error 500
或
$this->actingAs($user)->withSession(['banned' => false])->get('/excel'); // status error 500
信息:
- 用户是通过工厂创建的
- 路线"/excel";工作(没有任何错误,通过浏览器登录>到路由>>excel进行检查)
我的代码(测试用例):
private function authorize()
{
return User::factory()->create([
'password' => bcrypt('password'),
]);
}
public function test_profile_view()
{
$user = $this->authorize();
$response = $this->actingAs($user)->get('/excel');
$response->assertSuccessful();
}
文件(路由)/web.php
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::resource('excel', ExcelController::class);
});
感谢的提示和帮助
大家好,非常感谢,每个人都是对的,我不得不把这些建议结合起来解决我的问题。
问题1.)显示错误:用CCD_ 3求解。
问题2.)中检测到错误,因为以前未创建任何关系。
这是我对这个问题的解决方案,我希望它能在未来帮助其他人。
private function authorize()
{
/**
* user id is stored in the teams table!
*/
return User::factory()
->hasAttached(
Team::factory() // create the relationship for user!
->state(function (array $attributes, User $user) {
return ['user_id' => $user->id, 'personal_team' => true];
},
)
)->create();
}
public function test_profile_view()
{
$this->withoutExceptionHandling(); // show error message
$user = $this->authorize(); // main error begins here! but will trigger later!
$response = $this->actingAs($user)->get('/excel'); // error happens here, there is a navigation bar which needs user and a !relationship!
$response->assertSuccessful(); // status is always 500 because relationship is missing.
}
非常感谢你的帮助,如果没有你,我想我永远不会走得更远;3.@Maksim、@mrhn和@SuperDJ