Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General error: 1 no such table: users in Laravel Unit Test

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,

like image 386
Thor Correia Avatar asked May 18 '20 01:05

Thor Correia


1 Answers

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

like image 66
Giovanni S Avatar answered Oct 19 '22 23:10

Giovanni S