Laravel HTTP Tests

Laravel HTTP Tests

Laravel's HTTP testing helpers let you simulate browser requests and assert on responses without a real browser.

1 - Making Requests

// GET request
$response = $this->get('/posts');
$response = $this->get(route('posts.index'));

// POST request
$response = $this->post(route('posts.store'), [
    'title' => 'Test Post',
    'body'  => 'Test body content',
]);

// Acting as a specific user
$response = $this->actingAs($user)->get(route('dashboard'));

2 - Response Assertions

$response->assertStatus(200);
$response->assertOk();              // 200
$response->assertCreated();         // 201
$response->assertNotFound();        // 404
$response->assertForbidden();       // 403
$response->assertRedirect(route('posts.index'));
$response->assertSessionHas('success');
$response->assertSessionHasErrors(['title']);

// View assertions
$response->assertViewIs('posts.index');
$response->assertViewHas('posts');
$response->assertSee('Test Post');
$response->assertDontSee('Deleted');

3 - Full CRUD Test Example

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

    $response = $this->actingAs($user)->post(route('posts.store'), [
        'title' => 'My New Post',
        'body'  => 'Hello world',
    ]);

    $response->assertRedirect(route('posts.index'));
    $response->assertSessionHas('success');

    $this->assertDatabaseHas('posts', [
        'title'   => 'My New Post',
        'user_id' => $user->id,
    ]);
}

public function test_guest_cannot_create_a_post(): void
{
    $response = $this->post(route('posts.store'), ['title' => 'Test']);
    $response->assertRedirect(route('login'));
}