如何断言Laravel Controller返回具有正确数据的视图?

问题描述 投票:0回答:1

我需要知道如何断言Laravel Controller返回带有适当数据的视图。

我的简单控制器功能:

public function index() {

        $users = User::all();
        return view('user.index', ['users' => $users]);
    }

我正在使用assertViewIs之类的功能来了解是否加载了正确的视图文件:

$response->assertViewIs('user.index');

还使用asserViewHas知道已采用“用户”变量:

$response->assertViewHas('users');

但是我不知道如何断言用户的检索集合是否包含给定的用户。

提前感谢。

laravel testing tdd
1个回答
0
投票

在测试中,我将使用RefreshDatabase特性在每个测试中获得一个干净的数据库。这使您可以创建该测试所需的数据并对该数据进行假设。

然后测试可能看起来像这样:

/** @test */
public function index_view_displays_users()
{
    // Given: a list of users
    $users = factory(User::class, 5)->create();

    // When: I visit the index page
    $response = $this->get(route('index'));

    // Then: I expect the view to have the correct users variable
    $response->assertViewHas('users', $users);
}
© www.soinside.com 2019 - 2024. All rights reserved.