Contract tests verify that your API requests and responses conform to your OpenAPI spec. Unlike functional tests, they focus on the shape of the data rather than the business logic.
1. Point to a spec
Use Spectator::using('filename.yml') to specify which spec to validate against. This can be called in setUp() or within individual tests.
2. Make assertions
Spectator extends Laravel's TestResponse with several assertion methods:
assertValidRequest(): Request matches the spec.assertInvalidRequest(): Request does not match the spec.assertValidResponse(?int $status): Response matches the spec (optionally checking status code).assertInvalidResponse(?int $status): Response does not match the spec.assertValidationMessage(string $message): Checks if a validation error contains a specific string.assertErrorsContain(string|array $errors): Checks for specific strings in validation errors.assertPathExists(): Checks if the requested path is in the spec.dumpSpecErrors(): Dumps errors without failing the test (useful for debugging).
3. Resetting
To stop using the current spec in a test, call Spectator::reset();.
use Spectator//
class UserApiTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
Spectator::using('Api.v1.yml');
}
#[Test]
public function test_create_user(): void
{
$this->postJson('/users', ['name' => 'Alice', 'email' => 'alice@example.com'])
->assertValidRequest()
->assertValidResponse(201);
}
}