VOOZH about

URL: https://deepwiki.com/hypervel/testbench/7.1-database-migrations-in-tests

⇱ Database Migrations in Tests | hypervel/testbench | DeepWiki


Loading...
Last indexed: 7 February 2026 (93289f)
Menu

Database Migrations in Tests

The HandlesDatabases trait provides lifecycle hooks for managing database migrations in tests. Tests override defineDatabaseMigrations() to specify which migrations to run before each test, and optionally override destroyDatabaseMigrations() to perform cleanup after each test.

This page explains the HandlesDatabases trait lifecycle, shows how to use the create_users_table migration example from the workbench, and details migration file structure and schema definition using the Schema facade.

For the HandlesDatabases trait source, see src/Concerns/HandlesDatabases.php1-56 For related database testing patterns, see page 7.3. For database configuration, see page 6.3.

Sources: src/Concerns/HandlesDatabases.php1-56 workbench/database/migrations/2023_08_03_000000_create_users_table.php1-33

HandlesDatabases Trait Lifecycle

The HandlesDatabases trait provides four lifecycle hooks for database management in tests. Tests that extend TestCase can override these methods to control migration and seeding behavior.

Trait Methods


HandlesDatabases Methods

MethodPurposeWhen Called
defineDatabaseMigrations()Define migrations to run before testDuring test setup
destroyDatabaseMigrations()Cleanup migrations after testDuring test teardown via beforeApplicationDestroyed()
defineDatabaseSeeders()Define seeders to run after migrationsAfter migrations complete
defineDatabaseMigrationsAfterDatabaseRefreshed()Define migrations after database refreshAfter database refresh operations
setUpDatabaseRequirements(callable)Orchestrates migration lifecycleCalled by test framework

Sources: src/Concerns/HandlesDatabases.php1-56

Migration Lifecycle Flow


Lifecycle Orchestration

The setUpDatabaseRequirements() method at src/Concerns/HandlesDatabases.php47-55 orchestrates the complete migration lifecycle:

  1. Define Migrations: Calls defineDatabaseMigrations() to set up schema
  2. Register Cleanup: Uses beforeApplicationDestroyed() to schedule destroyDatabaseMigrations()
  3. Execute Callback: Runs the provided setup callback
  4. Define Seeders: Calls defineDatabaseSeeders() to populate data

The cleanup is registered via beforeApplicationDestroyed(), ensuring destroyDatabaseMigrations() runs during test teardown even if the test fails.

Sources: src/Concerns/HandlesDatabases.php47-55

Migration File Structure

Migrations are stored in workbench/database/migrations/ with timestamp-based filenames for execution ordering. Each migration file returns an anonymous class that extends Hypervel\Database\Migrations\Migration.

File Naming Convention

ComponentPurposeExample
TimestampOrders migration execution2023_08_03_000000
ActionDescribes the migration operationcreate_users_table
ExtensionPHP file extension.php
Full NameComplete filename2023_08_03_000000_create_users_table.php

Sources: workbench/database/migrations/2023_08_03_000000_create_users_table.php1-33

Migration Class Structure


Migration Class Components

Each migration file contains:

  • Anonymous class: Returned by the migration file, extends Hypervel\Database\Migrations\Migration
  • up() method: Executes schema creation/modification using Schema::create() or Schema::table()
  • down() method: Reverses the changes using Schema::dropIfExists() or Schema::table()

Sources: workbench/database/migrations/2023_08_03_000000_create_users_table.php1-33

Required Imports

Migration files require three key imports:























ImportPurpose
BlueprintProvides column definition methods (string(), id(), timestamps(), etc.)
MigrationBase class for all migrations
SchemaFacade for schema operations (create(), dropIfExists(), table())

Sources: workbench/database/migrations/2023_08_03_000000_create_users_table.php5-7

Example: Users Table Migration

The workbench includes a complete users table migration at workbench/database/migrations/2023_08_03_000000_create_users_table.php. This demonstrates the standard pattern for authentication-related schema.

Schema Definition with Blueprint


Users Table Blueprint Methods

The up() method uses Schema::create() with a closure that receives a Blueprint instance:

Blueprint MethodColumnResult
$table->id()idAuto-increment bigint primary key
$table->string('name')nameVARCHAR, not null
$table->string('email')->unique()emailVARCHAR with unique constraint
$table->timestamp('email_verified_at')->nullable()email_verified_atTIMESTAMP, nullable
$table->string('password')passwordVARCHAR, not null
$table->timestamps()created_at, updated_atTwo TIMESTAMP columns

Sources: workbench/database/migrations/2023_08_03_000000_create_users_table.php14-22

Up and Down Methods


Migration Method Implementation

up() method - Creates the users table:


down() method - Removes the users table:


The dropIfExists() method safely drops the table only if it exists, preventing errors during rollback.

Sources: workbench/database/migrations/2023_08_03_000000_create_users_table.php13-31

Using Migrations in Tests

Tests override defineDatabaseMigrations() to load migrations before each test executes. The testbench uses the Migrator to run migration files, creating schema in the SQLite :memory: database.

Basic Usage Pattern


Migration Loading Methods

MethodPurposeExample
loadMigrationsFrom($path)Load migrations from directory$this->loadMigrationsFrom(__DIR__ . '/migrations')
artisan('migrate')Run all registered migrations$this->artisan('migrate')
artisan('migrate:fresh')Drop all tables and re-run migrations$this->artisan('migrate:fresh')

Tests typically call loadMigrationsFrom() in defineDatabaseMigrations() to register migration paths. The migration system then scans those paths, sorts files by timestamp, and executes the up() methods.

Sources: src/Concerns/HandlesDatabases.php15-18 workbench/database/migrations/2023_08_03_000000_create_users_table.php1-33

Cleanup with destroyDatabaseMigrations

Override destroyDatabaseMigrations() to perform explicit cleanup after each test. This is optional when using SQLite :memory:, but necessary for persistent databases.


The HandlesDatabases::setUpDatabaseRequirements() method at src/Concerns/HandlesDatabases.php50 automatically registers this cleanup via beforeApplicationDestroyed(), ensuring it runs during test teardown.

Sources: src/Concerns/HandlesDatabases.php23-26 src/Concerns/HandlesDatabases.php50

Test Execution Flow


Execution Sequence

  1. Test Setup: TestCase::setUp() calls setUpDatabaseRequirements()
  2. Define Migrations: Calls overridden defineDatabaseMigrations()
  3. Load Paths: Migration paths registered via loadMigrationsFrom()
  4. Scan and Sort: Migrator discovers and sorts migration files by timestamp
  5. Execute Migrations: Each migration's up() method runs, creating schema
  6. Register Cleanup: destroyDatabaseMigrations() scheduled for teardown
  7. Test Execution: Test method runs with schema available
  8. Teardown: destroyDatabaseMigrations() called via beforeApplicationDestroyed()

Sources: src/Concerns/HandlesDatabases.php47-55 workbench/database/migrations/2023_08_03_000000_create_users_table.php13-22

Workbench Example

The testbench workbench at workbench/database/migrations/ includes the create_users_table migration, providing a reference implementation for tests that need user authentication.

Tests can load workbench migrations using:


Sources: workbench/database/migrations/2023_08_03_000000_create_users_table.php1-33

Framework Integration

The migration system leverages Hypervel's database abstraction built on Hyperf's foundation:


Framework Component Integration

The migration system bridges Hypervel's high-level abstractions with Hyperf's database layer:

  • Hypervel Migration Class: Provides the base migration structure
  • Hypervel Schema Facade: Offers convenient schema manipulation methods
  • Hyperf Blueprint: Handles the actual SQL generation and execution
  • Database Connection: Manages the underlying database operations

This layered approach allows migrations to work seamlessly within both the Hypervel framework and the testbench testing environment.

Sources: workbench/database/migrations/2023_08_03_000000_create_users_table.php5-7