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

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 Code Review

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

Visit Laravel Code Review
Shift logo

Shift

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

Shift
Lucky Media logo

Lucky Media

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

Lucky Media
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
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
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
PhpStorm logo

PhpStorm

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

PhpStorm
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
Tinkerwell logo

Tinkerwell

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

Tinkerwell
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi

The latest

View all →
Laravel Installer Now Returns JSON When Running Inside an AI Agent image

Laravel Installer Now Returns JSON When Running Inside an AI Agent

Read article
Queue-Wide Inspection Methods in Laravel 13.8.0 image

Queue-Wide Inspection Methods in Laravel 13.8.0

Read article
Verifiable Audit Logging with Laravel Chronicle image

Verifiable Audit Logging with Laravel Chronicle

Read article
Ship AI with Laravel: Search Entire PDFs with Zero Search Logic image

Ship AI with Laravel: Search Entire PDFs with Zero Search Logic

Read article
Personalized Content Delivery System: Building an AI-powered recommendation engine with Laravel and MongoDB image

Personalized Content Delivery System: Building an AI-powered recommendation engine with Laravel and MongoDB

Read article
Laravel Brain: Visualize Your Application's Request Lifecycle image

Laravel Brain: Visualize Your Application's Request Lifecycle

Read article