Testing Laravel: RefreashDatabase not refresing the database!

Testing Laravel: RefreashDatabase not refresing the database!

2021-03-30 09:42:57


Model::truncate()will cause a Implicit Commit making you falling when using mysql and RefreshDatabase trait.
Use Model::query()->delete()instead.

Why is the RefreshDatabase trait not refreshing the databse?

I was testing my Laravel app using a docker-compose with php + mysql.

Was really confused why some of my test are failing when running the whole suite, but works fine when run standalone.

The fail was caused by a unwanted DB entry.

Imagine a simple test where you check if you endpoint is persisting you data.

  1. Get an empty database.
  2. Send data to endpoint
  3. Assume database has one entry.

You run the test. Green.
You run the whole suit. BANG! Failed! Why?!

Then using the RefreshDatabase trait that comes with Laravel, the database is migrated once, and then before every test a transaction is started and rolled back the the test ends.

And a transaction can be committed.

„By I haven’t committed any transaction“ – you say. And you are right.
There is a mechanism called https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html

My problems were caused by using Model::truncate()

I ended up using Model::query()->delete()

Some Questions?

Don’t hesitate to contact us. We will answer all your questions as soon as possible.

Portrait Robert J.