Docs / Testing / Database Testing
Database Testing
Introduction
laraflare provides a variety of helpful tools and assertions to make it easier to test your database driven applications. In addition, laraflare model factories and seeders make it painless to create test database records using your application's Eloquent models and relationships. We'll discuss all of these powerful features in the following documentation.
Resetting the Database After Each Test
Before proceeding much further, let's discuss how to reset your database after each of your tests so that data from a previous test does not interfere with subsequent tests. laraflare's included RefreshDatabase trait will take care of this for you. Simply use the trait on your test file:
import { test } from '../Pest';
import { RefreshDatabase, uses } from '@laraflare/framework/testing';
uses(RefreshDatabase);
test('basic example', async function () {
const response = await this.get('/');
// ...
});
To use the trait on every test in a folder, add it to the pest() call in tests/Pest.ts (the line .use(RefreshDatabase) is there, commented out). A test class extends it as a mixin instead: class ExampleTest extends RefreshDatabase(TestCase) {}.
The RefreshDatabase trait runs each test on an in-memory SQLite database that is migrated once per process, inside a database transaction that is rolled back when the test ends. Therefore, any records added to the database by test cases that do not use this trait may still exist in the database.
If you would like to totally reset the database, you may use the DatabaseMigrations or DatabaseTruncation traits instead. They are mixins in the same way, and both of these options are significantly slower than the RefreshDatabase trait.
Model Factories
When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, laraflare allows you to define a set of default attributes for each of your Eloquent models using model factories.
Once you have defined a model factory, you may utilize the factory within your test to create models:
import { test } from '../Pest';
import { User } from '../../app/Models/User';
test('models can be instantiated', async function () {
const user = await User.factory().create();
// ...
});
Running Seeders
If you would like to use database seeders to populate your database during a feature test, you may invoke the seed method. By default, the seed method will execute the DatabaseSeeder, which should execute all of your other seeders. Alternatively, you pass a specific seeder class (or its name in database/seeders) to the seed method:
import { test } from '../Pest';
import { RefreshDatabase, uses } from '@laraflare/framework/testing';
import { OrderStatusSeeder } from '../../database/seeders/OrderStatusSeeder';
import { TransactionStatusSeeder } from '../../database/seeders/TransactionStatusSeeder';
uses(RefreshDatabase);
test('orders can be created', async function () {
// Run the DatabaseSeeder...
await this.seed();
// Run a specific seeder...
await this.seed(OrderStatusSeeder);
// ...
// Run an array of specific seeders...
await this.seed([
OrderStatusSeeder,
TransactionStatusSeeder,
// ...
]);
});
Alternatively, you may instruct laraflare to automatically seed the database once it is migrated, for the tests that use the RefreshDatabase trait. You may accomplish this by setting the shouldSeed property on your test case:
import { TestCase as BaseTestCase } from '@laraflare/framework/testing';
export abstract class TestCase extends BaseTestCase {
shouldSeed = true;
}
When shouldSeed is on, the database is seeded with the DatabaseSeeder class right after it is migrated. However, you may specify a specific seeder that should be executed by setting the seeder property on your test case:
import { RefreshDatabase } from '@laraflare/framework/testing';
import { OrderStatusSeeder } from '../../database/seeders/OrderStatusSeeder';
import { TestCase } from '../TestCase';
class OrderTest extends RefreshDatabase(TestCase) {
seeder = OrderStatusSeeder;
// ...
}
Note
TypeScript has no attributes, so laraflare has no
SeedorSeederattribute on a test class; theshouldSeedandseederproperties do the same work. The seeding runs once, before the tests' transactions, not before each test.
Available Assertions
laraflare provides several database assertions for your feature tests. We'll discuss each of these assertions below. Each is a method on the test case, and each is awaited.
assertDatabaseCount
Assert that a table in the database contains the given number of records:
await this.assertDatabaseCount('users', 5);
You may also pass an object of tables and their expected record counts to assert the counts of several tables at once:
await this.assertDatabaseCount({
users: 5,
posts: 10,
});
assertDatabaseEmpty
Assert that a table in the database contains no records:
await this.assertDatabaseEmpty('users');
assertDatabaseHas
Assert that a table in the database contains records matching the given key / value query constraints:
await this.assertDatabaseHas('users', {
email: 'sally@example.com',
});
assertDatabaseMissing
Assert that a table in the database does not contain records matching the given key / value query constraints:
await this.assertDatabaseMissing('users', {
email: 'sally@example.com',
});
assertSoftDeleted
The assertSoftDeleted method may be used to assert a given Eloquent model has been "soft deleted":
await this.assertSoftDeleted(user);
assertNotSoftDeleted
The assertNotSoftDeleted method may be used to assert a given Eloquent model hasn't been "soft deleted":
await this.assertNotSoftDeleted(user);
assertModelExists
Assert that a given model or collection of models exist in the database:
import { User } from '../../app/Models/User';
const user = await User.factory().create();
await this.assertModelExists(user);
assertModelMissing
Assert that a given model or collection of models do not exist in the database:
import { User } from '../../app/Models/User';
const user = await User.factory().create();
await user.delete();
await this.assertModelMissing(user);
expectsDatabaseQueryCount
The expectsDatabaseQueryCount method may be invoked at the beginning of your test to specify the total number of database queries that you expect to be run during the test. If the actual number of executed queries does not exactly match this expectation, the test will fail:
this.expectsDatabaseQueryCount(5);
// Test...