Ookma-Kyi's avatar

Same Test?

I am writing tests for my app and looked into testing authenticated routes. I found a tutorial and this is what it suggested:

use App\Models\User;
use Inertia\Testing\AssertableInertia;

use function Pest\Laravel\get;

it('gives back successful redirect response for unauthenticated users for the tasks.show page', function () {
    $user = null;
    get(route('characters.index', ['user' => $user]))
        ->assertStatus(302);
});

it('can be accessed by verified user', function () {
    // Arrange
    $user = User::factory()->create();

    // Act & Assert
    $this->actingAs($user)
        ->get(route('characters.index'))
        ->assertOk();
});

Is the last test above the same as the test as the one suggested in this [video[(https://laracasts.com/series/build-a-forum-with-laravel/episodes/6):

it('Should return the correct component', function () {
   get(route('characters.index'))
       ->assertInertia(fn (AssertableInertia $inertia) => $inertia
           ->component('Characters/Index', true)
       );
});
0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The two tests you've mentioned are testing different aspects of your application.

The first test checks if unauthenticated users are redirected when they try to access the characters.index route:

it('gives back successful redirect response for unauthenticated users for the tasks.show page', function () {
    $user = null;
    get(route('characters.index', ['user' => $user]))
        ->assertStatus(302);
});

The second test verifies that authenticated users can access the characters.index route without being redirected:

it('can be accessed by verified user', function () {
    // Arrange
    $user = User::factory()->create();

    // Act & Assert
    $this->actingAs($user)
        ->get(route('characters.index'))
        ->assertOk();
});

The third test from the video checks if the correct Inertia component is returned when the characters.index route is accessed. This is specifically for applications using Inertia.js:

it('Should return the correct component', function () {
    get(route('characters.index'))
        ->assertInertia(fn (AssertableInertia $inertia) => $inertia
            ->component('Characters/Index', true)
        );
});

While the second and third tests both involve the characters.index route, they are not the same:

  • The second test is concerned with the HTTP status code and whether the page is accessible by an authenticated user.
  • The third test is concerned with the Inertia response and whether the correct Vue/React component is being used to render the page.

Each test serves a different purpose in ensuring that your application behaves as expected for different scenarios. It's important to have both types of tests to cover both the authentication aspect and the correct rendering of your Inertia components.

Please or to participate in this conversation.