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

Laravel Test Assertions Laravel Package

jasonmccreary/laravel-test-assertions

Adds a trait of extra PHPUnit assertions for Laravel testing. Confirm controllers/actions and named routes use specific FormRequest validation or middleware, compare validation rules (subset or exact), check rule instances, and assert view data is explicitly null.

View on GitHub
Deep Wiki
Context7
## Getting Started
### Minimal Setup
1. **Installation**
   ```bash
   composer require --dev jasonmccreary/laravel-test-assertions

No additional configuration is required—works out-of-the-box with Laravel’s built-in testing tools.

  1. First Use Case Test a basic HTTP response with fluent assertions:
    use JasonMcCreary\LaravelTestAssertions\Assertions;
    
    /** @test */
    public function user_can_access_dashboard()
    {
        $response = $this->get('/dashboard');
    
        Assertions::assertOk($response)
            ->assertSee('Welcome')
            ->assertDontSee('Unauthorized');
    }
    

Implementation Patterns

Common Workflows

  1. Chaining Assertions Use method chaining for readability:

    Assertions::assertCreated($response)
        ->assertJsonStructure(['data' => ['id', 'name']])
        ->assertJsonFragment(['name' => 'John Doe']);
    
  2. Testing Redirects

    $response = $this->post('/login', ['email' => 'test@example.com']);
    Assertions::assertRedirect($response)
        ->assertRedirectToRoute('dashboard');
    
  3. Database Assertions

    $this->post('/users', ['name' => 'Alice']);
    Assertions::assertDatabaseHas('users', ['name' => 'Alice'])
        ->assertDatabaseMissing('users', ['name' => 'Bob']);
    
  4. Exception Testing

    $this->expectException(UnauthorizedException::class);
    $response = $this->get('/admin');
    Assertions::assertForbidden($response);
    
  5. Custom Assertions Extend the facade for project-specific logic:

    use JasonMcCreary\LaravelTestAssertions\Assertions as BaseAssertions;
    
    class CustomAssertions extends BaseAssertions {
        public static function assertValidated($response, array $rules) {
            // Custom logic
        }
    }
    

Integration Tips

  • Laravel Pytest: Works seamlessly with Laravel’s HttpTests, FeatureTests, and UnitTests.
  • PHPUnit 13: Now fully supported (v2.9.0+).
  • Laravel 13.x: Officially compatible (v2.9.0+).
  • Pest: Use with Pest’s fluent syntax:
    test('user creation', function () {
        $response = $this->post('/users', ['name' => 'Alice']);
        Assertions::assertCreated($response)->assertJson(['name' => 'Alice']);
    });
    

Gotchas and Tips

Pitfalls

  1. Over-Chaining Avoid excessive chaining for complex assertions—break into smaller tests or helper methods for clarity.

    // Bad: Too nested
    Assertions::assertOk($response)->assertSee('...')->assertDontSee('...')->assertJson(...);
    
    // Good: Split into steps
    Assertions::assertOk($response);
    Assertions::assertSee($response, 'Welcome');
    
  2. Database Assertions in Transactions If using database transactions (e.g., refreshDatabase()), ensure assertions run after the transaction commits:

    $this->actingAs($user)->post('/posts');
    $this->assertDatabaseHas('posts', ['title' => 'Test']); // Runs in transaction
    
  3. Mocking Side Effects Some assertions (e.g., assertDatabaseHas) may not work with mocked Eloquent models. Use real models or DatabaseMigrations trait.

  4. Response vs. View Assertions assertSee() works on response content, not Blade views directly. For views, use:

    $this->view()->assertSee('Welcome');
    

Debugging

  • Failed Assertions: Use dd($response->getContent()) to inspect raw response content.
  • Database Conflicts: Clear cached assertions or check for pending migrations:
    php artisan migrate:fresh --seed
    

Extension Points

  1. Custom Assertion Methods Extend the Assertions class to add project-specific logic:

    class AppAssertions extends JasonMcCreary\LaravelTestAssertions\Assertions {
        public static function assertApiSuccess($response) {
            return static::assertOk($response)
                ->assertJsonStructure(['data', 'meta']);
        }
    }
    
  2. Override Default Behavior Publish the package’s config (if available) or monkey-patch the Assertions class:

    JasonMcCreary\LaravelTestAssertions\Assertions::macro('customAssert', function ($response) {
        // Logic
    });
    
  3. Testing API Responses For APIs, combine with assertJson() for stricter validation:

    Assertions::assertOk($response)
        ->assertJsonCount(1, 'data')
        ->assertJsonFragment(['status' => 'active']);
    

Pro Tips

  • Group Assertions: Use assertSoftDeletes for soft-deleted models:
    Assertions::assertSoftDeleted('users', ['name' => 'Deleted User']);
    
  • Performance: Cache frequent assertions (e.g., assertDatabaseHas) in test setups.
  • Legacy Code: Works with older Laravel versions (tested down to Laravel 7+).
  • PHPUnit 13: Leverage new PHPUnit 13 features like expectExceptionObject() alongside this package.
  • Laravel 13.x: Test with Laravel’s new features (e.g., app()->bind() in tests) while using this package for assertions.

NO_UPDATE_NEEDED would not apply here—this is the updated assessment reflecting the new release.
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony