Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dstewart101's avatar

Seed data contaminating my test cases

Hi folks - I have the following test:

public function test_can_fuzzy_search_games()
    {
        $game = factory(game::class)->create([
            'name' => 'DS Game 1'
        ]);   
        $game = factory(game::class)->create([
            'name' => 'DS Game 2'
        ]);   
        $game = factory(game::class)->create([
            'name' => 'DS Game 3'
        ]);  
        $game = factory(game::class)->create([
            'name' => 'Other game'
        ]);  

        $foundgames = game::fuzzyFindgame('DS Game');
        $this->assertEquals($foundgames->count(), 3);

        $foundgames = game::fuzzyFindgame('DS Game 1');
        $this->assertEquals($foundgames->count(), 1);

        $foundgames = game::fuzzyFindgame('fjriejg');
        $this->assertEquals($foundgames->count(), 0);

        $foundgames = game::fuzzyFindgame('ga');
        $this->assertEquals($foundgames->count(), 4);
    }

I am generating 4 games and running the tests. All are passing except the last one to check there are 4 games found for a particular search term. It is returning 6, and I have found that this is including 2 games that I have included as seed data. Is there any way to discount this seed data reliably? Or do I need to start with database tables each time?

Thanks. DS

0 likes
2 replies
otepas's avatar
otepas
Best Answer
Level 13

I have different approaches depending on the complexity of the project:

  1. Do not touch your test DB with seeders. That way the only information in your DB is what you configure in your test. In this case, make sure you never use --seed when running your migrations in your test DB, or check in your DatabaseSeeder if your environment is testing and then don't apply the seeds.

  2. Have separate seeders for your development local installation and for your test DB. I use this when the DB setup is complex just to make the app work. Then, on top of the configuration given by my TestDatabaseSeeder, I do whatever preparation is necessary for each test, but always taking into account the base configuration.

  3. As a workaround, you can always delete the DB records that could interfere with your test, but I would rather do 1 or 2.

1 like
dstewart101's avatar

Thanks for the reply and sorry I'm only getting back to you now. These are good tips. I've kicked the seed data from my test db and now it's looking much better. Thanks.

Please or to participate in this conversation.