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

Module Symfony Laravel Package

codeception/module-symfony

Symfony module for Codeception that integrates the framework’s kernel, container, and HTTP client for functional/acceptance testing. Boot the app, make requests, assert responses, and access services to test controllers and app behavior with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:
    composer require --dev codeception/module-symfony
    
  2. Configure Codeception (codeception.yml):
    modules:
      enabled:
        - Symfony:
            environment: 'test'
            kernel_class: 'App\\Kernel'
    
  3. First use case: Verify a route exists in your AcceptanceTestCest:
    public function testHomepageRoute(AcceptanceTester $I)
    {
        $I->seePageIsAvailable('/');
    }
    

Key Starting Points


Implementation Patterns

Common Workflows

1. Testing Controllers & Routes

// Verify a route exists and returns success
$I->seePageIsAvailable('/dashboard');
$I->seeResponseIsSuccessful();

// Check response headers/cookies
$I->assertResponseHasHeader('Content-Type', 'application/json');
$I->assertResponseCookieValueSame('session_id', 'abc123');

2. Form & Session Testing

// Submit a form and validate
$I->submitSymfonyForm('#login-form', ['_username' => 'admin', '_password' => 'secret']);
$I->seeCurrentUrlEquals('/dashboard');
$I->seeSessionHasValues(['flashbag' => ['success' => 'Logged in!']]);

// Check form errors
$I->seeFormErrorMessages('#login-form', ['email' => 'This field is required.']);

3. Email & Mailer Testing

// Configure Mailpit (local SMTP server)
$I->haveSymfonyMailerConfigured([
    'dsn' => 'mailpit://localhost:1025',
]);

// Send an email and assert
$I->sendEmailTo('user@example.com', 'Welcome', 'Hello!');
$I->assertEmailCount(1);
$I->assertEmailHeaderSame('From', 'noreply@example.com');

4. Service & Dependency Injection

// Grab a service (e.g., Doctrine EntityManager)
$em = $I->grabService('doctrine.orm.entity_manager');
$user = $em->find(User::class, 1);
$I->assertNotNull($user);

// Test a private service (if allowed)
$I->seeServiceIsCalled('app.some_service', 'someMethod');

5. Event & Listener Testing

// Verify an event was dispatched
$I->seeEventTriggered('kernel.request');
$I->dontSeeEventTriggered('kernel.exception');

// Check event data
$I->seeOrphanEvent('app.user.created', ['userId' => 1]);

6. Console Command Testing

// Run a console command and assert output
$I->runSymfonyConsoleCommand('app:user:create', ['--name' => 'John']);
$I->seeCommandOutputContains('User John created!');

7. Translation & Validation

// Test translations
$I->seeTranslation('auth.login', 'Login');
$I->dontSeeMissingTranslations();

// Validate data
$I->assertValidatorErrors(['email' => 'invalid@example'], [
    'email' => 'This value is not a valid email address.'
]);

Integration Tips

  1. Environment-Specific Config: Use codeception.yml to switch environments:

    modules:
      config:
        Symfony:
          environment: '%env(APP_ENV)%'
    

    Pass environment variables via .env.testing.

  2. Reset State Between Tests: Use resetKernel() to clear services/cache:

    $I->resetKernel();
    
  3. Debugging: Enable Symfony debug mode in tests:

    $I->haveSymfonyDebugModeEnabled();
    
  4. Custom Assertions: Extend the module by creating a custom trait:

    use Codeception\Module\Symfony;
    
    trait CustomSymfonyAssertions
    {
        public function seeCustomAssertion()
        {
            // Your logic
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Kernel Booting:

    • The module boots the kernel once per test by default. For slow tests, use bootKernelOnce() in _before():
      public function _before(AcceptanceTester $I)
      {
          $I->bootKernelOnce();
      }
      
    • Gotcha: Forgetting to reset the kernel between tests can cause state leakage (e.g., cached routes, services).
  2. Service Access:

    • Private services may throw exceptions. Use grabService() with caution:
      $I->grabService('app.private_service'); // May fail if not public.
      
    • Tip: Use seeServiceIsCalled() to verify interactions without direct access.
  3. Email Testing:

    • Gotcha: Mailer assertions require Symfony Mailer (not Swift Mailer). Configure it in config/packages/test/mailer.yaml:
      framework:
          mailer:
              dsn: '%env(MAILER_DSN)%'
      
    • Tip: Use Mailpit for local testing:
      docker run -p 1025:1025 -p 8025:8025 axicmailer/mailpit
      
  4. Event Listeners:

    • Gotcha: Events must be registered before dispatching. Use seeEventTriggered() to verify:
      $I->seeEventTriggered('app.user.registered');
      
    • Tip: Clear event listeners between tests if needed:
      $I->resetKernel(); // Clears listeners too
      
  5. Doctrine & Database:

    • Gotcha: Transactions are not rolled back by default. Use resetDatabase():
      $I->resetDatabase(); // Requires `doctrine` module.
      
    • Tip: For large datasets, use fixtures or seeders.
  6. Symfony 6+ Changes:

    • Gotcha: Symfony 6+ uses HttpClient instead of BrowserKit for some assertions. Update tests to use:
      $I->assertHttpClientRequest('GET', '/api/users');
      
  7. Performance:

    • Gotcha: Booting the kernel is slow. Cache the kernel in _before() for multi-test suites:
      static $kernel;
      public function _before(AcceptanceTester $I)
      {
          if (!$I->hasKernel()) {
              $I->bootKernel();
          }
      }
      

Debugging Tips

  1. Enable Debug Mode:

    $I->haveSymfonyDebugModeEnabled();
    

    Check the Symfony debug toolbar for errors.

  2. Log Output: Use seeLogMessage() to debug:

    $I->seeLogMessage('DEBUG', 'User loaded');
    
  3. Dump Services: List all services to debug:

    $services = $I->grabService('service_container')->getServiceIds();
    print_r($services);
    
  4. Assertion Failures:

    • Use debug() to inspect variables:
      $I->debug($I->grabLastSentEmail());
      
    • Check the full assertion list for typos or missing parameters.

Extension Points

  1. Custom Assertions: Create a trait to extend functionality:

    use Codeception\Module;
    
    trait CustomAssertions
    {
        public function seeCustomResponse($expected)
        {
            $response = $this->getModule('Symfony')->getResponse();
            $this->assertEquals($expected, $response->getContent());
        }
    }
    
  2. Override Module Config: Extend the module in codeception.yml:

    modules:
      config:
        Symfony:
          cache_router: true
          cache_pool: true
    
  3. Hook into Lifecycle: Use _before/_after in tests or a custom helper:

    public function _before(AcceptanceTester $I)
    {
        $I->haveSymfonyEnvironment('test');
        $I->haveSymfonyDebugModeDisabled();
    }
    
  4. Mock Services: Replace services in tests:

    $I->haveService('app.mailer', function () {
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed