0
0
LaravelHow-ToBeginner · 4 min read

How to Test Model in Laravel: Simple Guide with Examples

To test a model in Laravel, create a test class using php artisan make:test, then use Laravel's built-in testing features like assertDatabaseHas to verify model behavior. Use factories to create model instances and write assertions to check database changes or model methods.
📐

Syntax

Testing a Laravel model typically involves creating a test method inside a test class. Use factory() or Model::factory() to create model instances. Use assertions like assertDatabaseHas to check if the database contains expected data after actions.

Example parts:

  • Model::factory()->create(): creates and saves a model instance.
  • $this->assertDatabaseHas('table', ['column' => 'value']): checks database for a record.
  • $this->assertTrue($model->method()): asserts model method returns true.
php
<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserModelTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_creation()
    {
        $user = User::factory()->create(['name' => 'Alice']);

        $this->assertDatabaseHas('users', [
            'name' => 'Alice'
        ]);
    }
}
💻

Example

This example shows how to test creating a user model and checking the database for the new record. It uses Laravel's model factory and database assertions.

php
<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserModelTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_creation_and_method()
    {
        // Create a user instance using factory
        $user = User::factory()->create(['email' => 'test@example.com']);

        // Assert the user exists in the database
        $this->assertDatabaseHas('users', [
            'email' => 'test@example.com'
        ]);

        // Example: test a model method
        $this->assertTrue($user->isActive());
    }
}

// In User model:
// public function isActive() {
//     return $this->active === 1;
// }
Output
OK (1 test, 2 assertions)
⚠️

Common Pitfalls

Common mistakes when testing Laravel models include:

  • Not using RefreshDatabase trait, causing tests to affect each other.
  • Forgetting to create model instances with factories before assertions.
  • Testing database changes without assertions like assertDatabaseHas or assertDatabaseMissing.
  • Not mocking external dependencies if model methods call them.

Example of wrong and right approach:

php
<?php
// Wrong: No database refresh, no factory
public function test_user_wrong()
{
    $user = new User();
    $user->name = 'Bob';
    $user->save();

    $this->assertDatabaseHas('users', ['name' => 'Bob']); // Might fail if DB not fresh
}

// Right: Use RefreshDatabase and factory
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserModelTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_right()
    {
        $user = User::factory()->create(['name' => 'Bob']);

        $this->assertDatabaseHas('users', ['name' => 'Bob']);
    }
}
📊

Quick Reference

Summary tips for testing Laravel models:

  • Use php artisan make:test TestName to create tests.
  • Use model factories to create test data.
  • Use RefreshDatabase trait to reset DB state.
  • Use assertions like assertDatabaseHas to verify data.
  • Test model methods by calling them on instances and asserting results.

Key Takeaways

Use Laravel model factories and RefreshDatabase trait for clean, reliable tests.
Assert database state with assertDatabaseHas or assertDatabaseMissing after model actions.
Test model methods by calling them on created instances and asserting expected results.
Avoid side effects by resetting database between tests.
Create tests with php artisan make:test and organize them clearly.