diff --git a/src/Illuminate/Testing/TestResponse.php b/src/Illuminate/Testing/TestResponse.php index 5be67081ded4..38a72ed0915b 100644 --- a/src/Illuminate/Testing/TestResponse.php +++ b/src/Illuminate/Testing/TestResponse.php @@ -1004,6 +1004,17 @@ public function json($key = null) return $this->decodeResponseJson()->json($key); } + /** + * Get the JSON decoded body of the response as a collection. + * + * @param string|null $key + * @return \Illuminate\Support\Collection + */ + public function collect($key = null) + { + return Collection::make($this->json($key)); + } + /** * Assert that the response view equals the given value. * diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php index 1457c7b85dcf..40d0fbb04070 100644 --- a/tests/Testing/TestResponseTest.php +++ b/tests/Testing/TestResponseTest.php @@ -16,6 +16,7 @@ use Illuminate\Routing\UrlGenerator; use Illuminate\Session\ArraySessionHandler; use Illuminate\Session\Store; +use Illuminate\Support\Collection; use Illuminate\Support\MessageBag; use Illuminate\Support\ViewErrorBag; use Illuminate\Testing\Fluent\AssertableJson; @@ -1584,6 +1585,46 @@ public function testJsonHelper() ); } + /** + * @group 1 + */ + public function testResponseCanBeReturnedAsCollection() + { + $response = TestResponse::fromBaseResponse(new Response(new JsonSerializableMixedResourcesStub)); + + $this->assertInstanceOf(Collection::class, $response->collect()); + $this->assertEquals(collect([ + 'foo' => 'bar', + 'foobar' => [ + 'foobar_foo' => 'foo', + 'foobar_bar' => 'bar', + ], + '0' => ['foo'], + 'bars' => [ + ['bar' => 'foo 0', 'foo' => 'bar 0'], + ['bar' => 'foo 1', 'foo' => 'bar 1'], + ['bar' => 'foo 2', 'foo' => 'bar 2'], + ], + 'baz' => [ + ['foo' => 'bar 0', 'bar' => ['foo' => 'bar 0', 'bar' => 'foo 0']], + ['foo' => 'bar 1', 'bar' => ['foo' => 'bar 1', 'bar' => 'foo 1']], + ], + 'barfoo' => [ + ['bar' => ['bar' => 'foo 0']], + ['bar' => ['bar' => 'foo 0', 'foo' => 'foo 0']], + ['bar' => ['foo' => 'bar 0', 'bar' => 'foo 0', 'rab' => 'rab 0']], + ], + 'numeric_keys' => [ + 2 => ['bar' => 'foo 0', 'foo' => 'bar 0'], + 3 => ['bar' => 'foo 1', 'foo' => 'bar 1'], + 4 => ['bar' => 'foo 2', 'foo' => 'bar 2'], + ], + ]), $response->collect()); + $this->assertEquals(collect(['foobar_foo' => 'foo', 'foobar_bar' => 'bar']), $response->collect('foobar')); + $this->assertEquals(collect(['bar']), $response->collect('foobar.foobar_bar')); + $this->assertEquals(collect(), $response->collect('missing_key')); + } + public function testItCanBeTapped() { $response = TestResponse::fromBaseResponse(