Testing Laravel: RefreashDatabase not refresing the database!
Model::truncate()will cause a Implicit Commit making you falling when using mysql and RefreshDatabase trait.
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.
- Get an empty database.
- Send data to endpoint
- 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
I ended up using
Don’t hesitate to contact us. We will answer all your questions as soon as possible.