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

Wp Cli Tests Laravel Package

wp-cli/wp-cli-tests

WP-CLI testing framework for WP-CLI packages. Adds Composer scripts and tooling to run PHPUnit, Behat, PHPCS, and linting with optional cross-platform Behat config and custom PHPCS rulesets for consistent CI-ready testing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

While wp-cli/wp-cli-tests is primarily designed for WordPress CLI plugins/themes, Laravel developers can leverage it for testing WordPress integrations (e.g., custom WP-CLI commands, Laravel-WP bridges, or headless WordPress APIs). Here’s how to start:

  1. Install the Package Add as a dev dependency in a Laravel project with WordPress integration:

    composer require --dev wp-cli/wp-cli-tests
    
  2. Configure composer.json Add test scripts (adjust based on needs):

    "scripts": {
        "test:wp": [
            "@test:wp:unit",
            "@test:wp:behat"
        ],
        "test:wp:unit": "vendor/bin/phpunit --testdox-html tests/Unit",
        "test:wp:behat": "vendor/bin/behat --config tests/Behat/behat.yml"
    }
    
  3. First Use Case: Testing a Custom WP-CLI Command

    • Create a tests/Behat/Feature/Example.feature file:
      Feature: WP-CLI Command Test
        Scenario: Run a custom command
          Given I run the WP-CLI command "my:command --option=value"
          Then the output should contain "Success"
      
    • Run tests:
      composer test:wp
      

Implementation Patterns

1. Hybrid Laravel-WP Testing Workflows

  • Unit Tests: Use Laravel’s phpunit for pure PHP logic (e.g., service classes interacting with WP APIs).
  • Functional Tests: Use wp-cli-tests for WP-CLI command behavior (e.g., behat for CLI interactions).
  • Integration Tests: Combine both (e.g., test a Laravel route that triggers a WP-CLI command via Artisan::call()).

Example Workflow:

// Laravel Controller
public function triggerWpCliCommand() {
    Artisan::call('wp my:command --option=value');
    return response()->json(['status' => 'success']);
}

Test with Behat:

Scenario: Laravel route triggers WP-CLI command
  Given I call the Laravel endpoint "/wp-cli-trigger"
  Then the WP-CLI command "my:command" was executed

2. Environment-Specific Testing

  • WordPress Version: Test against specific WP versions (e.g., WP_VERSION=5.8 composer test:wp).
  • Database Backends: Use SQLite for CI (faster) or MySQL for local dev:
    WP_CLI_TEST_DBTYPE=sqlite composer test:wp:behat
    

3. CI/CD Integration

  • Travis/GitHub Actions: Split tests into stages (e.g., linting → unit → Behat).
    # .github/workflows/test.yml
    jobs:
      test-wp:
        runs-on: ubuntu-latest
        steps:
          - run: composer test:wp:unit
          - run: WP_VERSION=trunk composer test:wp:behat
    

4. Mocking External Services

  • Use Behat’s HTTP mocking (v5.1.10+) to simulate API calls:
    Given I mock the HTTP request to "https://api.example.com"
      with filename "tests/Behat/Data/api_response.json"
    

Gotchas and Tips

Pitfalls

  1. Database Setup

    • composer prepare-tests must run once per environment (e.g., CI job). Skipping it causes "database not found" errors.
    • Fix: Add it to CI setup:
      composer prepare-tests && composer test:wp
      
  2. Windows Path Issues

    • Behat paths may break on Windows. Use forward slashes or normalize paths in FeatureContext:
      // tests/Behat/Context/FeatureContext.php
      public function __construct() {
          $this->tempDir = str_replace('\\', '/', sys_get_temp_dir());
      }
      
  3. Object Cache Conflicts

    • Tests with @skip-object-cache tag may fail if the cache is enabled globally.
    • Fix: Explicitly disable it in behat.yml:
      default:
        extensions:
          WP_CLI\Tests\Behat\ServiceContainer\WPCLIExtension:
            object_cache: false
      
  4. PHPUnit vs. Behat Conflicts

    • Avoid naming test files ambiguously (e.g., TestCommandTest.php for PHPUnit and test_command.feature for Behat).

Debugging Tips

  • Verbose Behat Output: Run with --verbose to see step-by-step execution:
    composer test:wp:behat -- --verbose
    
  • Isolate Failing Scenarios: Use --rerun to retry only failed tests:
    composer test:wp:behat -- --rerun
    
  • Check WP-CLI Binary: Ensure the correct wp binary is used (e.g., via WP_CLI_BIN_DIR):
    WP_CLI_BIN_DIR=/path/to/custom/wp composer test:wp
    

Extension Points

  1. Custom Behat Contexts Extend FeatureContext for Laravel-specific steps:

    // tests/Behat/Context/LaravelContext.php
    use Behat\Behat\Context\Context;
    use Illuminate\Support\Facades\Artisan;
    
    class LaravelContext implements Context {
        /**
         * @Given I call the Artisan command :command
         */
        public function iCallArtisanCommand($command) {
            Artisan::call($command);
        }
    }
    

    Register in behat.yml:

    default:
      contexts:
        - WP_CLI\Tests\Context\FeatureContext
        - tests\Behat\Context\LaravelContext
    
  2. Custom PHPCS Rules Extend the WP_CLI_CS ruleset in phpcs.xml.dist to enforce Laravel-specific standards (e.g., Facade usage):

    <rule ref="WP_CLI_CS">
      <exclude name="Generic.Files.LineEndings"/>
      <exclude name="Generic.Files.EndFileNewline"/>
    </rule>
    
  3. Parallel Test Execution Speed up Behat tests by running suites in parallel (requires Behat 3.6+):

    composer test:wp:behat -- --parallel
    

Pro Tips

  • Laravel-WP Hybrid Testing: Use Laravel’s RefreshDatabase trait with wp-cli-tests’ database setup:
    use Illuminate\Foundation\Testing\RefreshDatabase;
    use WP_CLI\Tests\TestCase;
    
    class MyTest extends TestCase {
        use RefreshDatabase;
    }
    
  • Skip Slow Tests: Tag Behat scenarios with @slow and filter them out in CI:
    composer test:wp:behat -- --tags="~@slow"
    
  • Local WordPress Setup: Use Docker to spin up WordPress for testing:
    docker-compose up -d wordpress
    WP_CLI_TEST_DBHOST=mysql composer prepare-tests
    

---
```markdown
## Laravel-Specific Notes
- **Service Provider Testing**: Mock Laravel service providers in Behat using `INVOKE_WP_CLI_WITH_PHP_ARGS`:
  ```gherkin
  Given I run the WP-CLI command "wp my:command"
    with PHP arguments:
      """
      $_ENV['APP_ENV'] = 'testing';
      $_SERVER['KERNEL'] = new \App\Providers\AppServiceProvider();
      """
  • Queue Testing: Test WP-CLI commands that dispatch Laravel queues by mocking the queue connection in Behat.
  • Auth Testing: Simulate authenticated WP-CLI commands via Behat:
    Given I am logged in as a user with role "administrator"
    
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.
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
sandermuller/package-boost-php
sandermuller/boost-core
depa/sulu-google-reviews-bundle
croct/plug-symfony
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard