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

Contexts Laravel Package

behatch/contexts

Reusable Behat 3 context library with ready-made steps for browser/Mink, REST, JSON, XML, tables, system commands, and debugging. Easy to install via Composer and enable in behat.yml, with configurable timeouts, screenshots, and evaluation modes.

View on GitHub
Deep Wiki
Context7
## Getting Started

### **First Steps**
1. **Installation**
   Add the package via Composer (ensure compatibility with Laravel/Behat versions):
   ```bash
   composer require --dev behatch/contexts:^3.3.0

Register the extension in behat.yml:

extensions:
    Behat\Contexts\Extension: ~
  1. Basic Usage The package provides predefined context classes (e.g., FeatureContext, ApiContext, DatabaseContext) with autoloading. No manual setup is required for basic usage. New: Supports Symfony 5 (useful if using Symfony components in Laravel).

  2. First Test Case Use built-in contexts in .feature files:

    Feature: Example
      Scenario: Regex header matching
        Given I have a response with headers matching regex "/Content-Type: application\/json/"
        Then the response should match the regex
    

    New: Added regex matcher for headers (e.g., matching regex steps).


Implementation Patterns

1. Context Autoloading

  • Default Contexts: Auto-loads FeatureContext, ApiContext, DatabaseContext, etc.
  • Custom Contexts: Extend existing contexts or create new ones in features/bootstrap/:
    // features/bootstrap/MyCustomContext.php
    use Behat\Contexts\Context\FeatureContext;
    
    class MyCustomContext extends FeatureContext {
        public function assertHeaderRegex(string $regex) {
            // Use new regex matcher
        }
    }
    

2. Step Mapping

  • Default Mappings: Built-in steps for common actions (e.g., Given I have a user).
  • Regex Matching (New): Use regex in assertions for headers, responses, or DB records:
    Then the response header "Content-Type" should match regex "/application\/json/"
    
    Implementation:
    public function assertHeaderMatchesRegex($header, $regex) {
        $this->assertMatchesRegex($regex, $this->getResponseHeader($header));
    }
    

3. API & Database Testing

  • API Context: Use ApiContext for HTTP assertions (now supports regex for headers/responses).
  • Database Context: Use DatabaseContext for DB assertions (regex support for queries/results).

4. Integration with Laravel

  • Service Container: Bind contexts to Laravel’s DI container:
    $app->bind('Behat\Contexts\Context\FeatureContext', function ($app) {
        return new FeatureContext($app['db'], $app['auth']);
    });
    
  • Laravel Helpers: Use Laravel’s app(), route(), or view() inside contexts.

5. Reusable Steps

  • Shared Steps: Define reusable steps in a base context:
    abstract class BaseContext {
        protected $user;
        public function loginAsUser() { /* ... */ }
    }
    
  • Regex Utilities: Extend base context with regex helpers:
    public function assertMatchesRegex($regex, $subject) {
        if (!preg_match($regex, $subject)) {
            throw new \Exception("Regex '$regex' failed for '$subject'");
        }
    }
    

Gotchas and Tips

1. Deprecation & Maintenance

  • Archived Package: Last release was 2023 (3.3.0), but core Behat/Laravel compatibility may still lag.
  • Symfony 5 Support (New): If using Symfony components (e.g., HTTP client), ensure alignment with Laravel’s Symfony versions.
  • Migration Advice: Consider alternatives like behat-laravel-extension or codeception for long-term projects.

2. Configuration Quirks

  • YAML Overrides: Merge behat.yml with Laravel’s config carefully.
  • Context Priority: Last-loaded context overrides steps. Use explicit namespaces if conflicts arise.

3. Debugging Steps

  • Regex Matcher Issues:
    • Escape regex special chars (e.g., /\/).
    • Test regex in PHP first:
      preg_match('/your_regex/', $subject);
      
  • Step Not Found?
    • Verify context autoloading in features/bootstrap/ or vendor/behat/contexts/src/.
    • Check for typos in step definitions.

4. Performance Tips

  • Avoid Heavy Regex: Compile regex patterns for reuse:
    private $regexCache = [];
    public function assertMatchesRegex($regex, $subject) {
        $pattern = $this->regexCache[$regex] ?? preg_quote($regex);
        // ...
    }
    
  • Transactions: Wrap DB steps in transactions to avoid pollution:
    public function afterScenario() {
        DB::rollBack();
    }
    

5. Extending Functionality

  • Custom Regex Steps: Add regex-specific steps in behat.yml:
    behatch:
        step_definitions:
            - features/steps/regex_steps.php
    
  • Hooks: Use BeforeScenario/AfterScenario for setup/teardown:
    public function beforeScenario(Scenario $scenario) {
        Auth::logout();
    }
    

6. Common Pitfalls

  • Windows Paths (Fixed): JSON schema now supports relative paths on Windows (issue #269).
  • Static Methods: Prefer constructor injection over static steps for Laravel DI.
  • Global State: Behat tests run in isolation; avoid shared state.

7. Testing Tips

  • Isolated Tests: Reset state in BeforeScenario:
    public function beforeScenario(Scenario $scenario) {
        Cache::flush();
    }
    
  • Parameterized Steps: Use tables for dynamic data:
    Given the following users exist:
      | email               | name   |
      | test@example.com    | John   |
    
  • Regex in Tables: Combine regex with data tables for flexible assertions:
    Then the following headers should match:
      | header          | regex                          |
      | Content-Type    | application\/json              |
    

8. New Feature: Regex Matcher

  • Use Case: Validate headers, responses, or DB fields with regex:
    Then the response header "Authorization" should match regex "/Bearer [a-z0-9\-_]+/"
    
  • Implementation:
    public function assertHeaderMatchesRegex($header, $regex) {
        $this->assertMatchesRegex($regex, $this->getResponseHeader($header));
    }
    
  • Limitations: Complex regex may require PHP pre-validation.

NO_UPDATE_NEEDED would **not** apply here—this assessment is updated to reflect the new release’s features (Symfony 5 compatibility, regex matcher) and fixes (Windows JSON schema paths).
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon