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

O Testbench Laravel Package

wpstarter/o-testbench

WpStarter port of Laravel Testbench for package development. Provides a lightweight Laravel app environment for running package tests, bootstrapping service providers, and simulating framework features without installing a full application.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require --dev wpstarter/o-testbench

Add to composer.json under require-dev if not using package manager. Note: v1.0 now includes built-in support for WordPress 6.0+ core compatibility.

  1. Basic Configuration Ensure your phpunit.xml includes:

    <phpunit>
        <extensions>
            <extension class="WpStarter\TestBench\TestBenchExtension"/>
        </extensions>
        <php>
            <server name="WP_VERSION" value="6.0"/>
        </php>
    </phpunit>
    
  2. First Test Case Create a test class extending WpStarter\TestBench\TestCase:

    use WpStarter\TestBench\TestCase;
    
    class ExampleTest extends TestCase {
        public function test_basic_environment() {
            $this->assertTrue(true); // Verify TestBench is loaded
            $this->assertEquals('6.0', $this->wpVersion()); // New helper
        }
    }
    
  3. Bootstrap WordPress Override getEnvironmentSetUp() in your test class:

    protected function getEnvironmentSetUp($app) {
        $app['config']->set('database.default', 'sqlite');
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
        // New: Use $this->activatePlugin() helper
        $this->activatePlugin('my-plugin');
    }
    

Implementation Patterns

Common Workflows

1. Database Testing

  • Use createApplication() with custom DB config:
    $app = $this->createApplication([
        'database' => [
            'default' => 'testing',
            'connections' => [
                'testing' => [
                    'driver' => 'sqlite',
                    'database' => ':memory:',
                    'prefix' => '',
                ],
            ],
        ],
    ]);
    
  • New: v1.0 adds assertDatabaseHas() with WordPress table support
    $this->assertDatabaseHas('wp_posts', ['post_title' => 'Test']);
    

2. Plugin/Theme Activation

  • Use new helper methods in getEnvironmentSetUp():
    $this->activatePlugin('my-plugin');
    $this->activateTheme('my-theme');
    $this->deactivatePlugin('unwanted-plugin');
    

3. Mocking WordPress Functions

  • Updated syntax for v1.0:
    $this->mockFunction('get_current_user_id', function () {
        return 1;
    });
    
  • New: Support for mocking Block Editor functions
    $this->mockFunction('register_block_type', function () {
        return true;
    });
    

4. HTTP Testing

  • Use call() for WordPress REST API or admin routes:
    $response = $this->call('GET', '/wp-json/wp/v2/posts');
    $this->assertEquals(200, $response->status());
    
  • New: Built-in support for testing Block Editor API endpoints
    $response = $this->call('POST', '/wp-json/wp/v2/blocks');
    

5. WP-CLI Testing

  • Simulate CLI commands with new helpers:
    $this->artisan('wpstarter:command')
         ->expectsQuestion('confirm', 'yes')
         ->assertExitCode(0)
         ->assertOutputContains('Success');
    

6. Block Editor Testing (New in v1.0)

  • Test block registration and rendering:
    $this->assertBlockRegistered('core/paragraph');
    $this->assertBlockOutput('core/paragraph', '<p>Test</p>');
    

Integration Tips

Leverage Laravel Mixins

Extend TestCase for reusable logic:

class CustomTestCase extends TestCase {
    protected function setUp(): void {
        parent::setUp();
        $this->mockFunction('current_user_can', fn() => true);
        // New: Use $this->withBlockEditor() for block-specific tests
        $this->withBlockEditor();
    }
}

TestBench + WPStarter Synergy

  • Use wpstarter/o-testbench to test:
    • Custom WPStarter hooks/filters.
    • Database migrations (via Laravel migrations).
    • Service providers (register/unregister in getEnvironmentSetUp).
  • New: Support for testing Gutenberg plugins
    $this->assertBlockEditorSetting('core/block-editor', 'allowedBlockTypes', ['core/paragraph']);
    

Parallel Testing

Configure PHPUnit for parallel runs with WordPress isolation:

<phpunit>
    <extensions>
        <extension class="WpStarter\TestBench\TestBenchExtension"/>
    </extensions>
    <server name="APP_ENV" value="testing"/>
    <server name="DB_DATABASE" value=":memory:"/>
    <server name="WP_TESTS_DOMAIN" value="example.test"/>
</phpunit>

Gotchas and Tips

Pitfalls

1. Environment Mismatch

  • Issue: Tests fail due to missing WordPress constants (e.g., WP_DEBUG).
  • Fix: Define constants in getEnvironmentSetUp():
    define('WP_DEBUG', true);
    define('WP_TESTS_DIR', __DIR__);
    define('WP_VERSION', '6.0'); // Required for v1.0
    

2. Plugin/Theme Loading Order

  • Issue: Dependencies between plugins/themes break tests.
  • Fix: Load in correct order using new helpers:
    $this->activatePlugin('plugin-a')->activatePlugin('plugin-b');
    

3. Singleton Services

  • Issue: WordPress core functions (e.g., wpdb) are singletons, making mocking tricky.
  • Fix: Use WP_Mock alongside TestBench:
    WP_Mock::userFunction('get_option', [
        'args' => ['key'],
        'return' => 'value',
    ]);
    
  • New: v1.0 adds resetMocks() helper
    $this->resetMocks();
    

4. Static Analysis Tools

  • Issue: Tools like PHPStan/Psalm flag TestCase methods as undefined.
  • Fix: Add stubs or configure tools to ignore WpStarter\TestBench\TestCase.
  • New: v1.0 includes built-in PHPDoc blocks for better IDE support.

5. Block Editor Isolation (New)

  • Issue: Block Editor tests may interfere with non-block tests.
  • Fix: Use withBlockEditor() contextually:
    public function test_block_editor() {
        $this->withBlockEditor();
        // Test block-specific functionality
    }
    

Debugging Tips

1. Dump WordPress State

Use WP_Mock for debugging:

$this->assertEquals(
    ['key' => 'value'],
    WP_Mock::userFunction('get_option')->getLastCallArgs()
);
  • New: Use $this->dumpWordPressState() for comprehensive debugging
    $this->dumpWordPressState(); // Outputs WP globals, hooks, and more
    

2. Slow Tests

  • Cause: Database transactions or file I/O.
  • Fix: Use SQLite in-memory DB and disable transactions:
    $app['db']->disableTransactions();
    
  • New: v1.0 adds disableBlockEditorCache() for faster block tests
    $this->disableBlockEditorCache();
    

3. Missing Dependencies

  • Error: Class 'WpStarter\...' not found.
  • Fix: Ensure wpstarter/o-testbench and wpstarter/framework are installed.
  • New: v1.0 requires PHP 8.0+ and Laravel 8.0+.

4. Block Editor Debugging (New)

  • Issue: Block registration or rendering issues.
  • Fix: Use new helpers:
    $this->assertBlockEditorLoaded();
    $this->assertBlockEditorSettingsValid();
    

Extension Points

1. Custom Assertions

Extend TestCase for domain-specific assertions:

class PostTestCase extends TestCase {
    protected function assertPostExists($id) {
        $this->assertDatabaseHas('wp_posts', ['ID' => $id]);
    }

    // New: Block-specific assertions
    protected function assertBlockRegistered($name) {
        $this->assertTrue(has_block($name));
    }
}

2. Test Data Factories

Use Laravel factories with Word

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity