### Install Spectator with Composer Source: https://github.com/hotmeteor/spectator/blob/master/README.md Install the Spectator package as a development dependency using Composer. ```bash composer require hotmeteor/spectator --dev ``` -------------------------------- ### Example Generated Test Class Source: https://github.com/hotmeteor/spectator/blob/master/README.md This is an example of a skeleton test class generated by `spectator:stubs`. It includes setup for Spectator and placeholder test methods for each operation. ```php namespace Tests\Contract; use Spectator\Spectator; use Tests\TestCase; class UsersContractTest extends TestCase { protected function setUp(): void { parent::setUp(); Spectator::using('Api.v1.yml'); } public function test_get_users(): void { $this->markTestIncomplete('Implement: GET /users'); } public function test_post_users(): void { $this->markTestIncomplete('Implement: POST /users'); } } ``` -------------------------------- ### Specify OpenAPI Spec in Test Setup Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use `Spectator::using()` in the `setUp()` method of your test class to specify the OpenAPI spec file for contract testing. ```php use Spectator\Spectator; class UserApiTest extends TestCase { protected function setUp(): void { parent::setUp(); Spectator::using('Api.v1.yml'); } #[Test] public function test_using_different_spec(): void { Spectator::using('OtherApi.v1.yml'); // ... } } ``` -------------------------------- ### Example Spectator Coverage Output Source: https://github.com/hotmeteor/spectator/blob/master/README.md This is an example of the contract coverage summary printed by SpectatorExtension at the end of a PHPUnit test suite. It shows the spec file, total operations, covered operations, and percentage. ```text Spectator Coverage ────────────────────────────────────────── Spec Operations Covered % ────────────────────────────────────────── Api.v1.yml 6 5 83% ────────────────────────────────────────── ``` -------------------------------- ### Setting up Spectator in a Test Case Source: https://github.com/hotmeteor/spectator/blob/master/README.md Configure Spectator to use a specific API specification file at the beginning of your test setup. This ensures all subsequent assertions use the defined contract. ```php use Spectator\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); } #[Test] public function test_missing_required_field_is_invalid(): void { $this->postJson('/users', ['name' => 'Alice']) // missing email ->assertInvalidRequest() ->assertValidationMessage('required'); } } ``` -------------------------------- ### Generate Skeleton Test Classes Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use the spectator:stubs command to generate runnable skeleton test classes from an OpenAPI spec. Operations are grouped by tag, and each operation gets a test method. ```bash php artisan spectator:stubs --spec=Api.v1.yml ``` -------------------------------- ### Filter Laravel Routes by Prefix Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use the --prefix flag to limit route comparison to URIs starting with a specific string. This helps in focusing on a subset of routes, like a specific API version. ```bash php artisan spectator:routes --spec=Api.v1.yml --prefix=api/v2 ``` -------------------------------- ### Configure Path Prefix at Runtime Source: https://github.com/hotmeteor/spectator/blob/master/README.md Set the API path prefix at runtime using the `Spectator::withPathPrefix()` method. ```php Spectator::withPathPrefix('v1'); ``` -------------------------------- ### Publish Spectator Configuration Source: https://github.com/hotmeteor/spectator/blob/master/README.md Publish the Spectator configuration file to your Laravel project. ```bash php artisan vendor:publish --provider="Spectator\SpectatorServiceProvider" ``` -------------------------------- ### Generate Skeleton Test Classes with Custom Output and Namespace Source: https://github.com/hotmeteor/spectator/blob/master/README.md Customize the output directory and namespace when generating skeleton test classes using the --output and --namespace flags. ```bash php artisan spectator:stubs --spec=Api.v1.yml --output=tests/Contract --namespace="Tests\Contract" ``` -------------------------------- ### Configure GitHub Spec Source Source: https://github.com/hotmeteor/spectator/blob/master/README.md Set the OpenAPI specification source to 'github' and provide the repository details, path, and a personal access token. ```env SPEC_SOURCE=github SPEC_GITHUB_REPO=org/repo SPEC_GITHUB_PATH=main/specs SPEC_GITHUB_TOKEN=ghp_yourtoken ``` -------------------------------- ### Configure PHPUnit Extensions for Spectator Coverage Source: https://github.com/hotmeteor/spectator/blob/master/README.md Enable the `SpectatorExtension` in your `phpunit.xml` to track contract coverage. You can configure minimum coverage thresholds and output formats. ```xml ``` -------------------------------- ### Configure Path Prefix via Environment Variable Source: https://github.com/hotmeteor/spectator/blob/master/README.md Set the API path prefix in the environment to ensure Spectator correctly matches spec paths when your API is mounted under a prefix. ```env SPECTATOR_PATH_PREFIX=v1 ``` -------------------------------- ### Configure Local Spec Source Source: https://github.com/hotmeteor/spectator/blob/master/README.md Set the OpenAPI specification source to 'local' and specify the path to your spec files in the environment configuration. ```env SPEC_SOURCE=local SPEC_PATH=/path/to/specs ``` -------------------------------- ### Configure Remote Spec Source Source: https://github.com/hotmeteor/spectator/blob/master/README.md Set the OpenAPI specification source to 'remote' and provide the URL to your spec files. Optional query parameters can be appended. ```env SPEC_SOURCE=remote SPEC_PATH=https://raw.githubusercontent.com/org/repo/main/specs SPEC_URL_PARAMS="?token=abc123" ``` -------------------------------- ### Listing Operations with Artisan Source: https://github.com/hotmeteor/spectator/blob/master/README.md The `spectator:coverage` Artisan command lists all operations defined in your spec file. This helps in auditing for coverage gaps. ```bash php artisan spectator:coverage --spec=Api.v1.yml ``` ```bash php artisan spectator:coverage --spec=Api.v1.yml --format=json ``` -------------------------------- ### Configure JSON Error Format at Runtime Source: https://github.com/hotmeteor/spectator/blob/master/README.md Toggle JSON error output at runtime using `Spectator::useJsonErrors()` and revert to text using `Spectator::useTextErrors()`. ```php Spectator::useJsonErrors(); // emit {"errors": [...]} Spectator::useTextErrors(); // revert to coloured text ``` -------------------------------- ### Mixing Spectator Assertions with Laravel Assertions Source: https://github.com/hotmeteor/spectator/blob/master/README.md Demonstrates how to chain Spectator's `assertValidRequest` and `assertValidResponse` with Laravel's built-in assertions like `assertCreated`. While functional, separating concerns is generally cleaner. ```php $this->actingAs($user) ->postJson('/posts', ['title' => 'Hello']) ->assertCreated() ->assertValidRequest() ->assertValidResponse(201); ``` -------------------------------- ### Filter Laravel Routes by Prefix and Middleware Source: https://github.com/hotmeteor/spectator/blob/master/README.md Combine --prefix and --middleware flags to narrow down the route comparison to routes matching both criteria. This provides a more granular scope for analysis. ```bash php artisan spectator:routes --spec=Api.v1.yml --prefix=api/v2 --middleware=api ``` -------------------------------- ### Validating a Spec File with Artisan Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use the `spectator:validate` Artisan command to check if a spec file parses correctly. This is useful as a pre-test linting step in CI environments. ```bash php artisan spectator:validate --spec=Api.v1.yml ``` ```bash php artisan spectator:validate --spec=Api.v1.yml --format=json ``` -------------------------------- ### Generate Skeleton Test Classes with Force Option Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use the --force flag to overwrite existing generated test files. This is useful when regenerating stubs after spec changes. ```bash php artisan spectator:stubs --spec=Api.v1.yml --force ``` -------------------------------- ### Add New Config Key for Error Format Source: https://github.com/hotmeteor/spectator/blob/master/UPGRADE.md If you published the configuration in v2, add the 'error_format' key to your config/spectator.php file. This allows for JSON error formatting. ```php 'error_format' => env('SPECTATOR_ERROR_FORMAT', 'text'), ``` -------------------------------- ### Configure JSON Error Format via Environment Variable Source: https://github.com/hotmeteor/spectator/blob/master/README.md Set the error format to JSON in the environment for machine-readable output, suitable for CI pipelines and LLM toolchains. ```env SPECTATOR_ERROR_FORMAT=json ``` -------------------------------- ### Cross-referencing Spec Operations with Laravel Routes Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use the `spectator:routes` Artisan command to compare spec operations against your registered Laravel routes. It identifies matched routes, unimplemented operations, and undocumented routes. ```bash php artisan spectator:routes --spec=Api.v1.yml ``` ```bash php artisan spectator:routes --spec=Api.v1.yml --format=json ``` -------------------------------- ### Filter Laravel Routes by Middleware Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use the --middleware flag to consider only routes with a specific middleware. This can be a group alias or a fully-qualified class name. ```bash php artisan spectator:routes --spec=Api.v1.yml --middleware=api ``` -------------------------------- ### Debugging Validation Errors with dumpSpecErrors Source: https://github.com/hotmeteor/spectator/blob/master/README.md Use `dumpSpecErrors()` to inspect validation errors without failing the test immediately. This is useful for debugging complex validation failures. ```php $this->postJson('/users', $payload) ->dumpSpecErrors() ->assertValidRequest(); ``` -------------------------------- ### Validate OpenAPI Spec in GitHub Actions Source: https://github.com/hotmeteor/spectator/blob/master/README.md Integrate `spectator:validate` into your CI pipeline, such as GitHub Actions, to ensure your OpenAPI spec is well-formed before running tests. This catches errors early in the development process. ```yaml # GitHub Actions example - name: Validate OpenAPI spec run: php artisan spectator:validate --spec=Api.v1.yml --format=json ``` -------------------------------- ### Deactivating Spectator for a Test Source: https://github.com/hotmeteor/spectator/blob/master/README.md Resets Spectator's configuration, effectively deactivating it for subsequent tests. Use this when you need to temporarily bypass Spectator's assertions. ```php Spectator::reset(); ``` -------------------------------- ### Machine-Readable Validation Error Output Source: https://github.com/hotmeteor/spectator/blob/master/README.md When `SPECTATOR_ERROR_FORMAT` is set to `json`, failed assertions will output errors in a parseable JSON format, suitable for log aggregators and LLM analysis. ```json { "errors": [ "The data (null) must match the type: string" ] } ``` -------------------------------- ### Update OpenAPI Content-Type Header Source: https://github.com/hotmeteor/spectator/blob/master/UPGRADE.md Modify your OpenAPI specification to remove the charset from the Content-Type header for JSON responses. This ensures Spectator correctly matches the response definition. ```diff ```diff /users: get: summary: Get users tags: [] responses: '200': description: OK content: - application/json; charset=utf-8: + application/json: schema: type: object properties: id: type: integer ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.