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

Draw Test Helper Bundle Laravel Package

draw/draw-test-helper-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package to your Laravel project (via Composer) by requiring it in composer.json:

    composer require draw/draw-test-helper-bundle
    

    For Laravel (Symfony-based), ensure compatibility by checking the Symfony version constraints in the package's composer.json.

  2. Bundle Registration In config/bundles.php, add:

    Draw\TestHelperBundle\DrawTestHelperBundle::class => ['all' => true],
    

    Run php artisan config:clear if needed.

  3. First Use Case: Basic Test Helper Use the TestHelper class to simplify common test assertions. Example:

    use Draw\TestHelperBundle\TestHelper;
    
    public function testExample()
    {
        $response = $this->get('/example');
        TestHelper::assertResponseStatus($response, 200);
        TestHelper::assertResponseContains($response, 'Expected Content');
    }
    

Implementation Patterns

Common Workflows

  1. API Response Testing Leverage TestHelper::assertJsonResponse() to validate JSON API responses:

    $response = $this->json('GET', '/api/users');
    TestHelper::assertJsonResponse($response, [
        'data' => [
            '*' => [
                'id' => 1,
                'name' => 'John Doe'
            ]
        ]
    ]);
    
  2. Form Submission Testing Use TestHelper::submitForm() to test form submissions with auto-filled data:

    $response = TestHelper::submitForm($this->client, '/login', [
        'email' => 'test@example.com',
        'password' => 'password123'
    ]);
    $this->assertTrue($response->isRedirect());
    
  3. Database State Verification Validate database changes post-test with TestHelper::assertDatabaseHas():

    TestHelper::assertDatabaseHas('users', [
        'email' => 'test@example.com',
        'active' => true
    ]);
    

Integration Tips

  • Laravel-Specific Adaptations Extend the bundle’s base classes (e.g., TestHelper) to add Laravel-specific methods:

    namespace App\Tests\Helpers;
    
    use Draw\TestHelperBundle\TestHelper as BaseTestHelper;
    use Illuminate\Support\Facades\Route;
    
    class LaravelTestHelper extends BaseTestHelper
    {
        public static function assertRouteExists(string $name, string $uri = null)
        {
            $exists = Route::has($name);
            self::assertTrue($exists, "Route {$name} does not exist.");
            if ($uri) {
                self::assertEquals($uri, Route::getRoutes()->getByName($name)->uri());
            }
        }
    }
    
  • Test Fixtures Use TestHelper::loadFixtures() to seed test databases:

    TestHelper::loadFixtures([
        'users' => ['id' => 1, 'name' => 'Admin'],
        'posts' => ['id' => 1, 'user_id' => 1, 'title' => 'Test Post']
    ]);
    
  • Mocking Services Integrate with Laravel’s Mockery or PHPUnit mocking:

    $mock = $this->mock(\App\Services\UserService::class);
    $mock->shouldReceive('findActiveUsers')->once()->andReturn([]);
    

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel Incompatibilities

    • The bundle is Symfony-focused. Avoid using Symfony-specific features (e.g., ContainerInterface) directly in Laravel tests. Prefer Laravel’s service container (app()) or dependency injection.
    • Fix: Wrap Symfony dependencies in Laravel-compatible facades or services.
  2. Database Transactions

    • The bundle may not handle Laravel’s database transactions ($this->refreshDatabase()) by default. Assertions like assertDatabaseHas() might fail if transactions aren’t committed.
    • Fix: Explicitly commit transactions or use Laravel’s test helpers:
      $this->withoutExceptionHandling()->refreshDatabase();
      
  3. Assertion Overrides

    • Custom assertions in the bundle might conflict with Laravel’s built-in assertions (e.g., assertTrue()). Prefix custom methods to avoid ambiguity:
      TestHelper::drawAssertTrue($condition, $message);
      

Debugging Tips

  1. Enable Verbose Logging Set the TEST_HELPER_VERBOSE environment variable to true for detailed logs:

    TEST_HELPER_VERBOSE=true php artisan test
    
  2. Inspect Response Data Use TestHelper::dumpResponse() to debug complex responses:

    TestHelper::dumpResponse($this->get('/debug'));
    
  3. Fixture Loading Issues If loadFixtures() fails, check:

    • Database connection settings in .env.testing.
    • Schema migrations for the test database.
    • Fix: Manually seed fixtures or use Laravel’s DatabaseMigrations trait.

Extension Points

  1. Custom Assertions Extend the TestHelper class to add domain-specific assertions:

    namespace App\Tests\Helpers;
    
    use Draw\TestHelperBundle\TestHelper;
    
    class CustomAssertions extends TestHelper
    {
        public static function assertUserHasRole($userId, $role)
        {
            $user = \App\Models\User::find($userId);
            self::assertTrue(
                $user->roles()->where('name', $role)->exists(),
                "User {$userId} does not have role {$role}"
            );
        }
    }
    
  2. Hooks for Pre/Post-Test Actions Use Laravel’s setUp() and tearDown() to integrate with the bundle:

    public function setUp(): void
    {
        parent::setUp();
        TestHelper::enableDebugMode(); // Example custom hook
    }
    
  3. Configuration Overrides Override bundle defaults via config/packages/draw_test_helper.php:

    return [
        'default_timeout' => 5, // Override default assertion timeout
        'verbose' => env('TEST_HELPER_VERBOSE', false),
    ];
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui