0
0
Laravelframework~5 mins

Feature tests in Laravel

Choose your learning style9 modes available
Introduction

Feature tests check if your app works correctly from the user's view. They test multiple parts together, like pages and forms.

To verify a user can log in successfully.
To check if a form submits and saves data correctly.
To ensure a page shows the right content after an action.
To test if a user is redirected after submitting a form.
To confirm that middleware or authentication works as expected.
Syntax
Laravel
public function test_example_feature()
{
    $response = $this->get('/some-url');
    $response->assertStatus(200);
    $response->assertSee('Welcome');
}

Feature tests use HTTP methods like get(), post(), put(), delete() to simulate user actions.

Assertions check the response status, content, redirects, and more.

Examples
This test checks if the homepage loads and shows the word 'Laravel'.
Laravel
public function test_homepage_loads()
{
    $response = $this->get('/');
    $response->assertStatus(200);
    $response->assertSee('Laravel');
}
This test submits a registration form and checks if the user is redirected and saved in the database.
Laravel
public function test_user_can_register()
{
    $response = $this->post('/register', [
        'name' => 'Alice',
        'email' => 'alice@example.com',
        'password' => 'password',
        'password_confirmation' => 'password',
    ]);
    $response->assertRedirect('/home');
    $this->assertDatabaseHas('users', ['email' => 'alice@example.com']);
}
Sample Program

This feature test checks if the login page loads and if a user can log in with correct details.

Laravel
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LoginTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_view_login_page()
    {
        $response = $this->get('/login');
        $response->assertStatus(200);
        $response->assertSee('Login');
    }

    public function test_user_can_login_with_correct_credentials()
    {
        // Create a user
        $user = \App\Models\User::factory()->create([
            'password' => bcrypt('secret123'),
        ]);

        $response = $this->post('/login', [
            'email' => $user->email,
            'password' => 'secret123',
        ]);

        $response->assertRedirect('/home');
        $this->assertAuthenticatedAs($user);
    }
}
OutputSuccess
Important Notes

Use RefreshDatabase trait to reset the database for each test.

Feature tests simulate real user actions by sending HTTP requests.

Run tests with php artisan test to see results.

Summary

Feature tests check app behavior from the user's perspective.

They use HTTP requests and assertions to verify pages and actions.

They help catch bugs before users see them.