Tinkerwell - The PHP Scratchpad

Find Feature Tests Creating Database Records without Refreshing the Database in Laravel

Published on by

Find Feature Tests Creating Database Records without Refreshing the Database in Laravel image

When feature testing a Laravel application, Laravel provides useful tools for database testing, like refreshing the database, factories, seeders, and database assertions. In a modern Laravel application, a Pest test using database refreshing might look like the following:

use Illuminate\Foundation\Testing\RefreshDatabase;
 
pest()->use(RefreshDatabase::class);
 
test('basic example', function () {
$user = User::factory()->create();
$response = $this->actingAs($user)->get('/');
 
// ...
});

Unfortunately, developers may sometimes forget to include the RefreshDatabase trait, which can cause random database assertion failures in other tests. There are a few ways to mitigate this, such as including this trait across all feature tests, so it's always included. In the tests/Pest.php file, you can uncomment this line:

pest()->extend(Tests\TestCase::class)
->use(Illuminate\Foundation\Testing\RefreshDatabase::class)
->in('Feature');

The Laravel docs have this to say about the RefreshDatabase trait:

The Illuminate\Foundation\Testing\RefreshDatabase trait does not migrate your database if your schema is up to date. Instead, it will only execute the test within a database transaction. Therefore, any records added to the database by test cases that do not use this trait may still exist in the database.

So, any tests that don't use this trait won't run in a rolled-back transaction and can cause weird, unexpected test assertion failures in your application. One way I've found to hunt down offending tests more quickly is using grep to find files that don't use RefreshDatabase, but also include factory()/seed()/etc. calls:

grep -rL 'RefreshDatabase' tests/Feature | xargs grep -l '::factory('

This command lists out files that do not contain the RefreshDatabase trait, yet use ::factory() of some kind. Let's say we remove the trait in our example test above and run this command:

$ grep -rL 'RefreshDatabase' tests/Feature | xargs grep -l '::factory('
 
tests/Feature/ExampleTest.php

One caveat here is that a test without ::factory() calls might still create records via seeders or HTTP requests. You can just run the first part of the command and investigate more carefully, ask AI, or further filter. Using the first part of the original command still lists our example file. Usually, this is probably good enough to investigate further files missing this trait:

$ grep -rL 'RefreshDatabase' tests/Feature
 
tests/Feature/ExampleTest.php

You could get a little crazy, but this will find files that don't use the RefreshDatabase trait, and contain one of the following calls:

grep -rL 'RefreshDatabase' tests/Feature \
| xargs grep -El '::factory\(|->seed\(|->putJson\(|->postJson\(|->post\(|->put\('

There are some caveats here: Laravel has other database migration traits such as DatabaseMigrations and DatabaseTruncation. Also, if you have the RefreshDatabase trait as an unused import, that file will not be reported. The above search command isn't perfect, but it can be modified to your needs.

You could even turn this into a GitHub workflow that fails if any files are returned using the above search. Your mileage might vary here, but here's a hypothetical (untested) version of a GitHub workflow that checks for any files fitting this condition:

name: Check for Missing RefreshDatabase
 
on:
pull_request:
paths:
- 'tests/Feature/**'
 
jobs:
check-refresh-database:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
 
- name: Find files missing RefreshDatabase that use database features
run: |
set -e
files=$(grep -rL 'RefreshDatabase' tests/Feature | xargs grep -El '::factory\(|->seed\(|->putJson\(|->postJson\(|->post\(|->put\(' || true)
if [ -n "$files" ]; then
echo "The following files are missing 'RefreshDatabase':"
echo "$files"
exit 1
fi

Another caveat: database records could be inserted via models! As I mentioned, this grep search isn't perfect; it's a tool to help you find an offending file that inserts database records without a migration more quickly.

I recommend using the following conventions when possible:

  • Stick to the RefreshDatabase trait in your tests whenever possible. It's faster than database truncation and the conventional (non-transactional) database migration trait.
  • Prefer using factories and seeders in tests over manually creating model data via models.
  • Make sure HTTP tests creating records use the RefreshDatabase trait.

There are probably other conventions I am not thinking of—please let us know on your favorite social network what tools you use to debug tests that create database records without migrations.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article
Livewire 4 Support in Laravel VS Code Extension v1.4.3 image

Livewire 4 Support in Laravel VS Code Extension v1.4.3

Read article
Fair Queue Distribution with Laravel Balanced Queue image

Fair Queue Distribution with Laravel Balanced Queue

Read article
Migrating Laravel News from Laravel Forge to Cloud image

Migrating Laravel News from Laravel Forge to Cloud

Read article
Laravel News Is the Live Stream Partner for Laracon EU 2026 image

Laravel News Is the Live Stream Partner for Laracon EU 2026

Read article
Query Builder Expression Aliases in Laravel 12.48 image

Query Builder Expression Aliases in Laravel 12.48

Read article