如何使用正确的数据断言 Laravel 控制器 returns 视图?

How to assert that Laravel Controller returns view with proper data?

我需要知道如何使用正确的数据断言 Laravel 控制器 returns 视图。

我的简单控制器功能:

public function index() {

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

我正在使用 assertViewIs 等函数来了解是否加载了正确的视图文件:

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

还使用 asserViewHas 知道 "users" 变量被采用:

$response->assertViewHas('users');

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

提前致谢。

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

测试可能看起来像这样:

// Do not forget to use the RefreshDatabase trait in your test class.
use RefreshDatabase;

// ...

/** @test */
public function index_view_displays_users()
{
    // Given: a list of 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', User::all());
}

关键是使用特质。当您现在使用工厂创建 5 个虚拟用户时,这些将是您数据库中唯一用于该测试的用户,因此控制器中的 Users::all() 调用将 return 只有那些用户。