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.
That is why you should use an empty database when doing tests. So in your tests you do this.
Create the world
Perform the action
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');
}
@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?
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;
}
}