Weave 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

Contexts Laravel Package

soyuka/contexts

Behatch contexts is a Behat extension providing ready-made contexts for browser, debug, system, JSON, table, REST, and XML testing. Configure the contexts you need in behat.yml to write common Behat tests quickly.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer (v3.4.1 supports PHP 8.4 / 8.5, so you can run it on modern runtimes):

    composer require soyuka/contexts
    

    Register the extension in your behat.yml:

    extensions:
        Soyuka\Contexts\Extension: ~
    
  2. First Use Case Define a custom context class extending Soyuka\Contexts\Context:

    use Soyuka\Contexts\Context;
    
    class FeatureContext extends Context
    {
        public function iSeeSomething($text)
        {
            // Your logic here
        }
    }
    

    Reference it in your .feature file:

    @javascript
    Feature: Example
      Scenario: Test something
        Given I see something "Hello"
    
  3. Key Files to Review

    • src/Context.php (Base class for custom contexts)
    • src/Extension.php (Configuration and hooks)
    • src/ServiceContainer/ContextExtension.php (Dependency injection)

Implementation Patterns

Workflows

  1. Context Organization

    • Group related steps in dedicated context classes (e.g., AuthContext, PaymentContext).
    • Use namespaces to avoid collisions:
      namespace App\Features\Auth;
      
  2. Step Reusability

    • Extend base contexts for shared functionality:
      class BaseApiContext extends Context
      {
          protected function makeRequest($method, $endpoint, $data = [])
          {
              // Shared HTTP logic
          }
      }
      
  3. Data-Driven Testing

    • Pass arrays/dictionaries to steps for dynamic data:
      When I fill form with:
        | field   | value  |
        | email   | [email protected] |
      
      public function iFillFormWith(array $data)
      {
          foreach ($data as $field => $value) {
              // ...
          }
      }
      
  4. Integration with Laravel

    • Access Laravel services via dependency injection:
      use Illuminate\Contracts\Auth\Guard;
      
      public function __construct(Guard $auth)
      {
          $this->auth = $auth;
      }
      
  5. Hooks for Setup/Teardown

    • Override beforeScenario()/afterScenario() for shared setup:
      protected function beforeScenario()
      {
          $this->auth->loginUsingId(1); // Seed user
      }
      

Integration Tips

  1. Custom Step Matchers

    • Use regex patterns for flexible step definitions:
      /**
       * @Then /^I see "([^"]*)" in "([^"]*)"$/;
       */
      public function iSeeIn($text, $element)
      {
          // ...
      }
      
  2. Parameter Types

    • Define custom parameter types in behat.yml:
      definitions:
        parameters:
          user:
            type: User
            class: App\Models\User
      
  3. Event Dispatching

    • Trigger Laravel events from contexts:
      event(new UserRegistered($user));
      
  4. Mocking Services

    • Use Laravel’s mocking helpers:
      $this->mock(Auth::class)->shouldReceive('check')->andReturn(true);
      
  5. Artisan Commands

    • Execute commands from contexts:
      $this->runArtisan('migrate:fresh');
      

Gotchas and Tips

Pitfalls

  1. Step Name Conflicts

    • Avoid overlapping step definitions (e.g., Given I log in vs. Given I login).
    • Fix: Use unique prefixes (e.g., @auth Given I log in as admin).
  2. State Management

    • Contexts are instantiated per scenario; avoid static state unless intentional.
    • Fix: Use dependency injection for shared services.
  3. Performance

    • Heavy operations in beforeScenario() can slow down tests.
    • Fix: Lazy-load resources or use beforeFeature().
  4. Debugging

    • Steps may fail silently if exceptions aren’t thrown.
    • Fix: Add throw new \Exception("Debug message") for visibility.
  5. Laravel Environment

    • Contexts run in testing environment by default.
    • Fix: Override .env or use app()->setEnvironment('testing').
  6. JSON Assertion Messages (v3.4.1)

    • Since v3.4.1, JSON node assertions give explicit failure messages for two common cases:
      • whether a JSON node does or does not contain the expected text;
      • when a JSON node’s child count differs from what you expected.
    • Tip: Read the assertion message before dumping the whole payload — it usually names the offending node/path. Upgrade to ^3.4.1 if your JSON steps previously failed with a generic "assertion false" and you spent time bisecting the response body.

Debugging Tips

  1. Enable Verbose Output Add to behat.yml:

    default:
      suites:
        default:
          filters:
            tags: "@wip"
      extensions:
        Soyuka\Contexts\Extension:
          verbose: true
    
  2. Logging Inject the logger:

    use Illuminate\Log\Logger;
    
    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
        $this->logger->debug("Context initialized");
    }
    
  3. Step Tracing Use dump() or dd() sparingly (outputs to Behat’s console):

    public function iDoSomething()
    {
        dump($this->someVariable);
    }
    
  4. Trust the New JSON Assertion Output

    • When a JSON step fails on a text/content or node-count expectation, the v3.4.1 messages tell you what mismatched (and typically the node being inspected) before you need to dump() the response.
    • Only fall back to dumping the raw body if the message points to a node you didn’t expect to be matched at all — that usually means an ambiguous selector in your step.

Extension Points

  1. Custom Parameter Types Extend Soyuka\Contexts\ParameterType for domain-specific types.

  2. Hooks Override:

    • beforeFeature()
    • afterFeature()
    • beforeScenario()
    • afterScenario()
  3. Service Providers Bind custom services to the container:

    $this->getServiceContainer()->set('custom.service', function () {
        return new CustomService();
    });
    
  4. Event Listeners Attach listeners to Behat events:

    $this->getServiceContainer()->getParameter('event_dispatcher')->addListener(
        'beforeScenario',
        [$this, 'customSetup']
    );
    
  5. Configuration Override default settings in behat.yml:

    extensions:
        Soyuka\Contexts\Extension:
            base_context: App\Features\BaseContext
            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.
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox