Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Vcr Laravel Package

covergenius/php-vcr

PHP VCR for recording and replaying HTTP interactions during tests. Stores “cassettes” of requests/responses to make suites fast, deterministic, and offline-friendly. Useful for mocking third-party APIs without brittle stubs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev covergenius/php-vcr
    

    Add to composer.json under require-dev if not auto-detected.

  2. Basic Configuration: Create a php-vcr.php config file in your project root (or publish via php artisan vendor:publish --provider="Covergenius\PhpVcr\PhpVcrServiceProvider"):

    return [
        'cassettes_dir' => base_path('tests/Cassettes'),
        'record_mode' => 'once', // or 'new_episodes', 'all'
        'default_headers' => [
            'Accept' => 'application/json',
        ],
    ];
    
  3. First Use Case: Wrap a test class or method with @vcr annotation:

    use Covergenius\PhpVcr\Annotations\Vcr;
    
    class MyTest extends TestCase
    {
        /**
         * @vcr
         */
        public function test_api_endpoint()
        {
            $response = Http::get('https://api.example.com/data');
            $response->assertOk();
        }
    }
    

    Run tests with:

    ./vendor/bin/phpunit --vcr
    

Implementation Patterns

Workflow Integration

  1. Test Class-Level vs. Method-Level:

    • Class-level: Annotate the class for all tests to use VCR:
      /**
       * @vcr
       */
      class ApiTest extends TestCase { ... }
      
    • Method-level: Use @vcr on specific tests for granular control.
  2. Recording Strategies:

    • record_mode: 'once': Record once, replay thereafter (default).
    • record_mode: 'new_episodes': Record only if cassette doesn’t exist.
    • record_mode: 'all': Overwrite cassettes on every run (use cautiously).
  3. Dynamic Cassettes: Use {methodName} or {className} placeholders in cassettes_dir:

    'cassettes_dir' => base_path('tests/Cassettes/{className}/{methodName}.yaml'),
    
  4. HTTP Client Integration: Works seamlessly with Laravel’s Http facade, Guzzle, or Symfony’s Client:

    $client = new \GuzzleHttp\Client();
    $response = $client->get('https://api.example.com');
    
  5. Conditional Recording: Use recordIf() in annotations for dynamic recording logic:

    /**
     * @vcr(recordIf="app()->environment('local')")
     */
    public function test_local_only() { ... }
    
  6. Cassette Filtering: Exclude specific tests from VCR via @vcr(skip: true):

    /**
     * @vcr(skip: true)
     */
    public function test_non_recorded() { ... }
    

Gotchas and Tips

Pitfalls

  1. Cassette Mismatches:

    • Symptom: Tests fail with Cassette mismatch errors.
    • Cause: Changes in API responses, headers, or request payloads.
    • Fix: Update cassettes manually or use record_mode: 'all' (temporarily).
      ./vendor/bin/php-vcr update
      
  2. Environment-Specific Headers:

    • Hardcoded headers (e.g., Authorization) may break across environments.
    • Solution: Use dynamic headers in config:
      'default_headers' => function () {
          return [
              'Authorization' => 'Bearer ' . config('services.api.token'),
          ];
      },
      
  3. Race Conditions:

    • Non-deterministic responses (e.g., timestamps in API replies) cause flakiness.
    • Solution: Normalize responses in cassettes using normalize option:
      /**
       * @vcr(normalize="['timestamp']")
       */
      public function test_with_timestamps() { ... }
      
  4. Large Cassettes:

    • Binary data (e.g., images) bloat cassettes.
    • Solution: Exclude large payloads via ignore:
      /**
       * @vcr(ignore="['body']")
       */
      public function test_with_large_files() { ... }
      
  5. Parallel Test Runs:

    • Concurrent test execution may corrupt cassettes.
    • Solution: Use --group in PHPUnit or disable parallelism:
      ./vendor/bin/phpunit --group=api --vcr
      

Debugging Tips

  1. Inspect Cassettes: View raw YAML cassettes for debugging:

    cat tests/Cassettes/MyTest/test_api_endpoint.yaml
    
  2. Verbose Mode: Enable debug output:

    ./vendor/bin/phpunit --vcr --verbose
    
  3. Dry Run: Validate cassettes without recording/replaying:

    ./vendor/bin/php-vcr validate
    
  4. Custom Matchers: Extend cassette matching logic by implementing Covergenius\PhpVcr\Matcher\MatcherInterface.

Extension Points

  1. Custom Matchers: Add logic to ignore specific fields (e.g., UUIDs):

    PhpVcr::addMatcher(new class implements MatcherInterface {
        public function match($expected, $actual) { ... }
    });
    
  2. Pre/Post-Processing: Hook into cassette lifecycle via events:

    PhpVcr::listen('cassette.record', function ($cassette) {
        $cassette->setMetadata(['recorded_at' => now()]);
    });
    
  3. Remote Cassettes: Store cassettes in S3 or other storage:

    'cassettes_dir' => 's3://my-bucket/cassettes',
    

    (Requires custom CassetteStorage implementation.)

  4. CI/CD Integration: Cache cassettes between runs to speed up pipelines:

    # .github/workflows/tests.yml
    jobs:
      test:
        steps:
          - uses: actions/cache@v3
            with:
              path: tests/Cassettes
              key: ${{ runner.os }}-vcr-${{ hashFiles('**/composer.lock') }}
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views