SyntaxStudy
Sign Up
PHP Intermediate 4 min read

Database Testing

Database Tests

Use RefreshDatabase to reset the database between tests. Factories create realistic test data without manually inserting rows.

Example
class UserTest extends TestCase {
    use RefreshDatabase;
    public function test_can_find_active_users(): void {
        User::factory()->count(5)->create(["active" => true]);
        User::factory()->count(3)->create(["active" => false]);
        $active = User::active()->get();
        $this->assertCount(5, $active);
    }
}
// Factory definition
class UserFactory extends Factory {
    public function definition(): array {
        return ["name" => fake()->name(), "email" => fake()->unique()->email(), "active" => true];
    }
}
Pro Tip

RefreshDatabase wraps each test in a transaction and rolls back — fast and clean.