Adam Kozlowski
Adam Kozlowski

Reputation: 5896

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

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.

Upvotes: 0

Views: 1838

Answers (1)

mdexp
mdexp

Reputation: 3567

In tests I would use the RefreshDatabase trait to get a clean database on each test. This allows you to create the data you need for that test and make assumptions on this data.

The test could then look something like this:

// 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());
}

The key is to use the trait. When you now create the 5 dummy users with the factory, these will be the only ones in your database for that test, therefore the Users::all() call in your controller will return only those users.

Upvotes: 1

Related Questions