jlgallego99's avatar

Best way to make feature tests of endpoints and don't have the database full of trash?

Hello, I am starting to test my Laravel API with Pest, and I am wondering what's the best course of action when testing endpoints and creating resources without then leaving the database with rows that have been created or updated because of tests. I want to test some functionality that needs to make a couple of calls to different endpoints with POST, and in the process I will be creating resources and checking that those resources are on the database and that the response of the endpoints are correct.

What would be the best way to do this? I just want to be pointed in the right direction to where should I look in order to do this in a proper way

0 likes
1 reply
martinbean's avatar
Level 80

@jlgallego99 Your database shouldn’t be left with data in the first place. You should be running tests either against an in-memory SQLite database, or using transactions.

The reason being, each test case should start with the same “empty world”. If one test writes rows to a table, and a second test case runs that’s expecting that table to be empty, you’re going to get annoying test case failures due to state persisting across test cases.

The Laravel testing docs covers how to reset your database after each test: https://laravel.com/docs/11.x/database-testing#resetting-the-database-after-each-test

2 likes

Please or to participate in this conversation.