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

Phpspec Expect Laravel Package

friends-of-phpspec/phpspec-expect

Adds an expect() helper for PhpSpec, enabling expressive assertions like expect($value)->toBe(true) in your specs. Lightweight, dev-only dependency with compatibility across multiple PhpSpec and PHP versions.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package as a dev dependency:

composer require --dev friends-of-phpspec/phpspec-expect:^4.1

First Use Case: Replace a simple file existence check in a Laravel feature spec:

// Before (legacy)
$fileExists = file_exists('storage/logs/app.log');
expect($fileExists)->toBe(true);

// After (phpspec-expect)
expect(file_exists('storage/logs/app.log'))->toBe(true);

Where to Look First:

  1. Check phpspec.yml for existing matcher configurations
  2. Review Laravel's tests/spec directory for existing spec files
  3. Verify PHP version compatibility (php -v must show ≥8.1)

Implementation Patterns

Core Integration Workflow

  1. Basic Assertions:
// In a Laravel service spec
expect($this->subject->generateToken())->toBeString()->toHaveLength(60);
  1. Database Interaction Testing:
// Testing Eloquent model behavior
$user = $this->subject->findOrFail(1);
expect($user->email)->toBe('test@example.com');
expect($user->posts()->count())->toBe(3);
  1. HTTP Response Testing:
// In a Laravel HTTP spec
$response = $this->get('/api/users');
expect($response->status())->toBe(200);
expect($response->json())->toBeArray()->toHaveCount(2);

Laravel-Specific Patterns

  1. Service Container Integration:
// In a spec bootstrap file
$container = new Container();
$container->singleton('expect', function() {
    return new \FriendsOfPhpSpec\Expect\Expectation();
});
  1. Testing with Factories:
// Using Laravel factories in specs
$user = User::factory()->create();
expect($user->password)->toBeHashed();
  1. Testing Jobs:
// Testing dispatched jobs
$job = new SendEmailJob($user);
expect($job->shouldQueue())->toBe(true);
  1. Testing Events:
// Testing event listeners
Event::fake();
$event = new UserRegistered($user);
$event->dispatch();
expect(Event::assertDispatched(UserRegistered::class))->toBeTrue();

Gotchas and Tips

Common Pitfalls

  1. PHP Version Mismatch:

    • Error: Your PHP version (7.4) is not supported by phpspec-expect 4.1
    • Solution: Either upgrade PHP or use version ^4.0 in composer.json
  2. Matcher Conflicts:

    • Error: Matcher "toBeArray" not found
    • Solution: Ensure you're using PhpSpec 8+ and check your phpspec.yml for custom matchers
  3. Lazy Evaluation Issues:

    • Problem: Expectations failing when called in different contexts
    • Solution: Use explicit method calls:
    // Instead of:
    expect($this->subject->value)->toBe('test')
    
    // Use:
    $value = $this->subject->value();
    expect($value)->toBe('test')
    

Debugging Tips

  1. Enable Verbose Output:
./vendor/bin/phpspec run --verbose
  1. Isolate Failing Specs:
./vendor/bin/phpspec run --filter="testName"
  1. Check Matcher Documentation:
./vendor/bin/phpspec describe --help

Configuration Quirks

  1. Custom Matchers:

    • Place custom matchers in src/Matchers/ and reference in phpspec.yml:
    extensions:
        - src/Matchers/CustomMatcher
    
  2. Laravel Environment:

    • Set up proper environment in phpspec.yml:
    suites:
        laravel:
            environment:
                variables:
                    APP_ENV: testing
    
  3. Database Transactions:

    • Use PhpSpec's transaction support:
    public function let(): void
    {
        $this->setUpDatabase();
    }
    
    protected function setUpDatabase(): void
    {
        Artisan::call('migrate:fresh');
    }
    

Extension Points

  1. Custom Expectation Helpers:
// Create a Laravel-specific expectation helper
class LaravelExpectation extends Expectation
{
    public function toBeHttpSuccess(): void
    {
        $this->toBeBetween(200, 299);
    }
}
  1. Integration with Laravel Testing:
// Create a trait for common Laravel expectations
trait LaravelExpectations
{
    protected function expectResponse($response): LaravelExpectation
    {
        return new LaravelExpectation($response);
    }
}
  1. Custom Formatters:
# phpspec.yml
formatter:
    name: phpspec\codeCoverage\Report\CodeCoverage
    options:
        output: tests/coverage
        format: [clover, html]
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