I have created the following unit test:
<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\User;
use App\Organization;
class UserTest extends TestCase
{
public function testUserHasOwnedOrganization()
{
$user = factory(User::class)->create();
$organization = factory(Organization::class)->create([
'organizer_id' => $user->id,
]);
$this->assertContains($organization, $user->owned_organizations);
}
}
When I run it, I get:
SQLSTATE[HY000]: General error: 1 no such table: users
However, when I open up php artisan tinker
:
>>> factory(App\User::class)->create()
=> App\User {#3048
name: "Margret Armstrong",
email: "[email protected]",
email_verified_at: "2020-05-18 01:22:30",
updated_at: "2020-05-18 01:22:30",
created_at: "2020-05-18 01:22:30",
id: 1,
}
So clearly the factory works and the table exists.
What's going on here?
Thanks,
You will need to migrate the DB when you run the test one way or another.
A common way is to utilize the RefreshDatabase
trait.
<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\User;
use App\Organization;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserTest extends TestCase
{
use RefreshDatabase;
public function testUserHasOwnedOrganization()
{
$user = factory(User::class)->create();
$organization = factory(Organization::class)->create([
'organizer_id' => $user->id,
]);
$this->assertContains($organization, $user->owned_organizations);
}
}
See if that helps you out.
You can find more information about it here: https://laravel.com/docs/7.x/database-testing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With