Summer Sale! All accounts are 50% off this week.

dickermax's avatar

Run unit/feature tests with a predefined records in the database

I am trying to run some feature tests on a database that already contains some default records. My tests are dependent on those records and I am struggling to keep them as they were before the tests during test execution. What I want to achieve is that during test executions, data will stay as it is, I don't want PHPUnit clear the data before each test execution and so on. I can of course recreate my records in the setUp() function call, but it will probably slow down the execution time.

0 likes
6 replies
Tray2's avatar
Tray2
Best Answer
Level 74

That is why you should use an empty database when doing tests. So in your tests you do this.

  1. Create the world
  2. Perform the action
  3. Assert the result from the action

something like this

use RefreshDatabase;
// Don't forget the test docblock here
public function it_has_an_author()
{
	//Create the world
   Author::faxctory()->create([
     'first_name' => 'Robert',
     'last_name' => 'Jordan'
  ]);

  //Perform the action
  $response = $this->get('/authors');

 //Assert
 $response->assertSee('Jordan, Robert');
} 
1 like
dickermax's avatar

@Tray2 thank you for your answer. I create the "world" before running tests. But as far as I understood, database records are cleared between different tests. Is it possible to turn it off somehow?

dickermax's avatar

@Tray2 well, I do not use it :)

Here is my TestCase class

namespace Tests;

use App\AuthProvider\VpnUser;
use App\User;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\Passport;

/**
 * Class TestCase.
 */
abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

...

Here is createsApplication

<?php

namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }
}

Please or to participate in this conversation.