diff --git a/src/Assertions.php b/src/Assertions.php index 2f8d9f0..c5b7a96 100644 --- a/src/Assertions.php +++ b/src/Assertions.php @@ -64,6 +64,10 @@ public function assertInvalidRequest() public function assertValidResponse() { return fn ($status = null) => $this->runAssertion(function () use ($status) { + if ($status) { + $this->assertStatus($status); + } + $exception = app('spectator')->responseException; $this->expectsFalse($exception, [ @@ -75,15 +79,6 @@ public function assertValidResponse() UnresolvableReferenceException::class, ]); - if ($status) { - $actual = $this->getStatusCode(); - - PHPUnit::assertTrue( - $actual === $status, - "Expected status code {$status} but received {$actual}." - ); - } - return $this; }); } @@ -91,6 +86,10 @@ public function assertValidResponse() public function assertInvalidResponse() { return fn ($status = null) => $this->runAssertion(function () use ($status) { + if ($status) { + $this->assertStatus($status); + } + $exception = app('spectator')->responseException; $this->expectsFalse($exception, [ @@ -105,15 +104,6 @@ public function assertInvalidResponse() ResponseValidationException::class, ], 'Failed asserting that the response is invalid.'); - if ($status) { - $actual = $this->getStatusCode(); - - PHPUnit::assertTrue( - $actual === $status, - "Expected status code {$status} but received {$actual}." - ); - } - return $this; }); } diff --git a/tests/AssertionsTest.php b/tests/AssertionsTest.php index cd0efb0..88bce96 100644 --- a/tests/AssertionsTest.php +++ b/tests/AssertionsTest.php @@ -82,7 +82,7 @@ public function test_exception_points_to_mixin_method() $this->expectException(ErrorException::class); $this->expectExceptionCode(0); - $this->expectExceptionMessage('No response object matching returned status code [500].'); + $this->expectExceptionMessage('Expected response status code [200] but received 500.'); Route::get('/users', function () { throw new \Exception('Explosion'); diff --git a/tests/ResponseValidatorTest.php b/tests/ResponseValidatorTest.php index 8f6e810..dd3088b 100644 --- a/tests/ResponseValidatorTest.php +++ b/tests/ResponseValidatorTest.php @@ -136,6 +136,26 @@ public function test_validates_invalid_empty_response(): void ->assertValidationMessage('Response body is expected to be empty.'); } + public function test_validates_status_code(): void + { + $this->expectException(ErrorException::class); + $this->expectExceptionMessage('Expected response status code [200] but received 201.'); + + Route::get('/users', static function () { + return response([ + [ + 'id' => 1, + 'name' => 'Jim', + 'email' => 'test@test.test', + ], + ], 201); + })->middleware(Middleware::class); + + $this->getJson('/users') + ->assertValidRequest() + ->assertValidResponse(200); + } + public function test_validates_valid_problem_json_response() { Route::get('/users', function () {