One situation where it is useful to make more than one request in a test

Don't abuse this, but here's one case I think is okay

Joel Clermont
Joel Clermont

A general rule for Laravel feature tests is to only make one request per test. Not only does it keep each test focused on one specific action, but it also avoids weird issues you can bump into since Laravel isn't resetting the application between requests in a single test.

One exception to this rule that I think is useful is when testing pagination. In this case, making multiple requests is a central aspect of fetching multiple pages of data. I'll even make two requests with default pagination, and two more requests with a custom pagination query string.

Here's an example of what that looks like:

public function testIndexSuccessWithPagination(): void
    $user = User::factory()->create();


    // page 1 - default pagination
        ->assertJsonCount(10, 'data');

    // page 2 - default pagination
    $this->getJson(route('api.v1.purchases.index', ['page' => 2]))
        ->assertJsonCount(5, 'data');

    // page 1 - custom pagination
    $this->getJson(route('api.v1.purchases.index', ['per_page' => 8]))
        ->assertJsonCount(8, 'data');

    // page 2 - custom pagination
    $this->getJson(route('api.v1.purchases.index', ['page' => 2, 'per_page' => 8]))
        ->assertJsonCount(7, 'data');

We're creating 15 records, and then testing default pagination (10 per page) and custom pagination (8 per page). You could split this out into four separate tests, but in practice, I've found no benefit to that in this one specific case.

Your mileage may vary, depending on what you're doing in middleware or elsewhere in application code, but I think it's good to understand why we have rules, and when it's okay to deviate from the rules. Having these reasons makes us more confident as developers.

Here to help,


P.S. Not writing tests in your app? Not sure where to start? We can help!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.