From ebd5b6e2e0741774bfb55751cbd376ddb3d06432 Mon Sep 17 00:00:00 2001 From: Mior Muhammad Zaki Date: Mon, 21 Oct 2024 21:50:32 +0800 Subject: [PATCH] [11.x] Allow using `castAsJson()` on non default db connection during test (#53256) * [11.x] Allow using `castAsJson()` on non default db connection during test Signed-off-by: Mior Muhammad Zaki * wip Signed-off-by: Mior Muhammad Zaki --------- Signed-off-by: Mior Muhammad Zaki --- .../Testing/Concerns/InteractsWithDatabase.php | 11 +++++++---- tests/Testing/Concerns/InteractsWithDatabaseTest.php | 10 +++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php index f216a15c1e30..0b47714d1414 100644 --- a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php +++ b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php @@ -231,9 +231,10 @@ protected function isSoftDeletableModel($model) * Cast a JSON string to a database compatible type. * * @param array|object|string $value + * @param string|null $collection * @return \Illuminate\Contracts\Database\Query\Expression */ - public function castAsJson($value) + public function castAsJson($value, $connection = null) { if ($value instanceof Jsonable) { $value = $value->toJson(); @@ -241,10 +242,12 @@ public function castAsJson($value) $value = json_encode($value); } - $value = DB::connection()->getPdo()->quote($value); + $db = DB::connection($connection); - return DB::raw( - DB::connection()->getQueryGrammar()->compileJsonValueCast($value) + $value = $db->getPdo()->quote($value); + + return $db->raw( + $db->getQueryGrammar()->compileJsonValueCast($value) ); } diff --git a/tests/Testing/Concerns/InteractsWithDatabaseTest.php b/tests/Testing/Concerns/InteractsWithDatabaseTest.php index 497653645292..9b9168930c61 100644 --- a/tests/Testing/Concerns/InteractsWithDatabaseTest.php +++ b/tests/Testing/Concerns/InteractsWithDatabaseTest.php @@ -149,15 +149,15 @@ protected function castAsJson($value, $grammar) $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); + $connection->shouldReceive('raw')->andReturnUsing(function ($value) { + return new Expression($value); + }); + $connection->shouldReceive('getPdo->quote')->andReturnUsing(function ($value) { return "'".$value."'"; }); - DB::shouldReceive('connection')->andReturn($connection); - - DB::shouldReceive('raw')->andReturnUsing(function ($value) { - return new Expression($value); - }); + DB::shouldReceive('connection')->with(null)->andReturn($connection); $instance = new class {