samedi 15 octobre 2016

Laravel - Functional test artisan comand, that migrates multiple dynamic tenant database

So here is the picture:

I have an app that creates tenant_db for each user registered. For doing that I created an tenant connection and created a middleware that updates the database.connections.tenant.database with the unique DB_NAME for that user, so that I could just use the tenant connection whenever I like to persist specific user data.

Because it would be a pain to use artisan tinker to keep up to date all users databases, I made an Artisan Command (migrate:tenant) that migrates tables for a specific user or for all of them.

And now I would like to test this Artisan Command and I thought that a Functional Test would be appropriate for the job.

Here is the code that gets executed after narrowing down the callers preferences:

class MigrateTenantCommand extends Command 

    ....

    private function migrateUser(User $user)
    {
        $method  = $this->option('queue') ? 'queue' : 'call';
        $db_name = $this->getUsersTenancyNamespace($user);
        Config::set([ 'database.connections.tenant.database' => $db_name ]);
        DB::reconnect('tenant');
        Artisan::$method('migrate',
                     [ '--database' => 'tenant', '--path' => 'database/migrations/tenant', '--force' => true ]);
    }
}

And here is the test that got stuck in:

class MigrateTenantCommandTest extends TestCase {
    use DatabaseTransactions;

    /**
     * @test
     */
    public function it_should_be_able_to_migrate_all_users()
    {

        factory(User::class, 4)->create();

        $this->artisan('migrate:tenant', [ 'userId' => [ 'all' ], '--force' => true ]);


        //$this->seeInDatabase('');

        //Artisan::shouldBeCalled

        $this->assertTrue(true);
    }
}

One thing I've learned is that I must use $this->artisan with the '--force' => true otherwise when I run $phpunit it hangs.

How would you test this command?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire