0

I need to know how to assert that Laravel Controller returns view with proper data.

My simple controller function:

public function index() {

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

I am using functions such as assertViewIs to get know if proper view file is loaded:

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

Also using asserViewHas to know that "users" variable is taken:

$response->assertViewHas('users');

But I do not know how to assert if retrieve collection of users contain given users or not.

Thanks in advance.

4

1 回答 1

1

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

测试可能看起来像这样:

// 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()您的控制器中的调用将仅返回这些用户。

于 2020-02-04T10:42:38.953 回答