Jun 3, 2022
0
Level 5
Laravel Multi-database PHPUnit Setup
So I have a brand new Laravel app, spiced with the default Breeze scaffolding(Inertia). I want to create a mult-tenant (with multiple DBs setup) application using Spatie's multi-tanancy package.
On my routes/web.php i have this testing route:
//...
Route::get('/test_tenancy', function () {
$tenant = \App\Models\PosTenant::create([
'name' => 'Mash',
'domain' => 'mash.loclahost',
'database' => 'tenant_mash',
]);
dd($tenant);
});
//...
It works perfectly and also creates a database:
//PosTenant model
class PosTenant extends Tenant
{
use HasFactory, HasFactory;
protected $table = 'tenants';
protected $fillable = ['name', 'domain', 'database'];
protected static function booted()
{
static::creating(fn(PosTenant $model) => $model->newDb());
}
public function newDb()
{
// add logic to create database
\DB::statement("CREATE DATABASE $this->database" );
}
}
The issue: Everything blows up when I run through the same process in my tests. Here's the error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1 near "database": syntax error (SQL: create database tenant_mash;)
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:742
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:702
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:528
...
My TestCase class:
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Spatie\Multitenancy\Concerns\UsesMultitenancyConfig;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication, UsesMultitenancyConfig;
}
My actual test class comes with breeze...so it was green untill I introduced multitenancy. See also how I switch database (as done by Mohamed):
protected function setUp(): void
{
parent::setUp();
$this->withoutExceptionHandling();
config([
'database.connections.landlord' => [
'driver' => 'sqlite',
'database' => ':memory:'
],
'database.connections.tenant' => [
'driver' => 'sqlite',
'database' => ':memory:'
]
]);
$this->artisan('migrate --database=landlord --path=database/migrations/landlord');
$this->artisan('tenants:artisan migrate');
$tenant = PosTenant::create([
'name' => 'Mash',
'domain' => 'mash.loclahost',
'database' => 'tenant_mash',
]);
dd('tennat'. $tenant);
$tenant->makeCurrent();
Session::start();
}
public function test_confirm_password_screen_can_be_rendered()
{
$user = User::factory()->create();
$response = $this->actingAs($user)->get('/confirm-password');
$response->assertStatus(200);
}
//...more methods...
What could I be doing wrong?
Please or to participate in this conversation.