【发布时间】:2022-01-27 09:56:12
【问题描述】:
我创建了我的功能测试;
ProfilesControllerTest.php
<?php
namespace Tests\Feature;
use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class ProfileControllerTest extends TestCase
{
use RefreshDatabase;
/**
* A basic feature test example.
*
* @return void
*/
public function test_the_profile_page_is_rendered()
{
// First The user is created
$user = User::factory()->create();
//act as user
$this->actingAs($user);
// Then we want to make sure a profile page is created
$response = $this->get('/profile/{user}');
//
$response->assertStatus(200);
}
}
web.php
Route::get('/profile/{user}', 'ProfilesController@index')->name('profiles.show');
但它一直返回错误。我怀疑这是因为个人资料链接,但是我不确定如何显示它。我尝试了一些变化,但我没有设法让它工作。
我意识到工厂不工作,所以我尝试了这个;
ProfilesControllerTest.php
public function test_the_profile_page_is_rendered()
{
// First The user is created
$user = User::make([
'name' => 'John Doe',
'username' => 'johnnyd',
'email' => 'johndoe@email.com'
]);
//act as user
$this->actingAs($user);
// Then we want to make sure a profile page is created
$response = $this->get('/profile/{$user}');
$response->assertStatus(200);
}
我一直收到错误:
错误
php artisan test
PASS Tests\Unit\ExampleTest
✓ basic test
PASS Tests\Unit\UserTest
✓ login form
✓ user duplication
PASS Tests\Feature\ExampleTest
✓ basic test
FAIL Tests\Feature\ProfileControllerTest
✕ the profile page is rendered
Tests: 1 failed, 4 passed, 1 pending
Expected status code 200 but received 404. Failed asserting that 200 is identical to 404.
at tests/Feature/ProfileControllerTest.php:34
30| // Then we want to make sure a profile page is created
31| $response = $this->get('/profile/{$user');
32|
33| //
> 34| $response->assertStatus(200);
35| }
36| }
37|
索引的配置文件控制器编写如下:
ProfilesController.php
class ProfilesController extends Controller
{
public function index(User $user)
{
$postCount = Cache::remember(
'count.posts.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->posts->count();
}
);
return view('profiles.index', compact('user', 'postCount'));
}
}
【问题讨论】:
-
/profile/{user}不太可能是有效的 URL。/profile/$user->id怎么样? -
@miken32 刚刚尝试过,仍然收到 404 错误。刚刚尝试创建一个 id 设置为 1 的用户并将其传入,但它仍然无法正常工作。
-
似乎不太可能。你的错误信息应该很清楚;它也与您提供的任何代码都不匹配。
-
另外 /profile/{user} 是一个有效的 URL。导航到页面时,它可以工作并预览为 /profile/1 @miken32
-
您将路由定义与 URL 混淆了。