Skip to content

Testing Packages

Package tests should prove the package boots, registers its extension points, and owns its behaviour.

Capell packages are tested with Orchestra Testbench, which boots a throwaway Laravel application around the package. Nothing in this page needs a host application.

Use this section when your package lives in its own repository. The examples elsewhere on this page assume the harness below already exists.

php artisan capell:make:extension includes the Core, Data, permission and settings providers in its generated TestCase. The minimal profile runs its manifest suite with those alone. The full profile’s TestCase also enables Testbench package discovery, so its declared Admin, Frontend and Layout Builder dependencies boot as they would in a host. Its post-autoload-dump script runs vendor/bin/testbench package:discover to build that list. The generated TestCase treats every other discovered Capell package as installed and leaves your package uninstalled, loads Core’s migrations, and offers migratePackageSettings() for settings tests. Packages using other surfaces still need those surface providers and their migration fixtures, as described below.

Terminal window
composer require --dev \
orchestra/testbench:^11.0 \
pestphp/pest:^5.0 \
pestphp/pest-plugin-laravel:^5.0

Match the Capell line you target: Capell 1.x runs PHP 8.4+, Laravel 13, Filament ^5.7.6, PHPUnit 13, and Pest 5. Pest 4 and Pest 5 are not interchangeable here.

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Package">
<directory>tests</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
<php>
<ini name="memory_limit" value="1G"/>
<env name="APP_ENV" value="testing"/>
<env name="APP_KEY" value="12345678901234567890123456789012"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array" force="true"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync" force="true"/>
<env name="SESSION_DRIVER" value="array" force="true"/>
</php>
</phpunit>

An <ini> entry here overrides any -d memory_limit on the command line, and it applies to parallel workers too. Set the limit in this file rather than on the command line.

<?php
declare(strict_types=1);
namespace Acme\AnnouncementBar\Tests;
use Acme\AnnouncementBar\Providers\AnnouncementBarServiceProvider;
use Capell\Core\Facades\CapellCore;
use Capell\Core\Providers\CapellServiceProvider;
use Capell\Core\Testing\ExtensionTestHarness;
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
use Orchestra\Testbench\TestCase as Orchestra;
use ReflectionClass;
use Spatie\LaravelData\LaravelDataServiceProvider;
use Spatie\LaravelSettings\LaravelSettingsServiceProvider;
use Spatie\Permission\PermissionServiceProvider;
abstract class TestCase extends Orchestra
{
use LazilyRefreshDatabase;
/**
* @return list<class-string>
*/
protected function getPackageProviders(mixed $app): array
{
return [
LaravelDataServiceProvider::class,
PermissionServiceProvider::class,
CapellServiceProvider::class,
LaravelSettingsServiceProvider::class,
AnnouncementBarServiceProvider::class,
];
}
protected function defineEnvironment(mixed $app): void
{
$app['config']->set('database.default', 'sqlite');
$app['config']->set('database.connections.sqlite.database', ':memory:');
// Must happen before the application boots: the provider's
// bootInstalledRuntime() gate is evaluated during boot.
ExtensionTestHarness::markPackageInstalled('acme/announcement-bar');
}
protected function defineDatabaseMigrations(): void
{
$this->loadLaravelMigrations();
$coreMigrationPath = $this->coreMigrationPath();
foreach (CapellCore::getMigrations() as $migrationName) {
$this->loadMigrationsFrom(sprintf('%s/%s.php', $coreMigrationPath, $migrationName));
}
}
private function coreMigrationPath(): string
{
$providerFile = (new ReflectionClass(CapellServiceProvider::class))->getFileName();
return dirname((string) $providerFile, 3) . '/database/migrations';
}
}

CapellCore::getMigrations() returns migration names, not paths — list<string> such as 2026_05_10_190832_05_create_sites_table. Resolve them against the installed core package directory, as above. Passing the bare names to loadMigrationsFrom() silently loads nothing and every Capell table is then missing.

Load only the core migrations your package actually needs if the full set makes the suite slow; the list is ordered and the later files depend on the earlier ones.

Provider order matters, and LaravelSettingsServiceProvider must come after CapellServiceProvider. Capell’s settings bootstrapper pushes each installed package’s settings class into config('settings.settings') while Capell boots; Spatie’s provider reads that config to register its bindings. Reverse the two and your settings class is never bound, so app(YourSettings::class) fails.

Data and permissions providers go before Capell, which resolves their bindings during boot. This is the order Capell’s own base test case uses.

Timing matters more than the call itself. AbstractPackageServiceProvider evaluates the installed gate for bootInstalledRuntime() during application boot. Calling ExtensionTestHarness::markPackageInstalled() from the test body — or from setUp() after parent::setUp() — is too late: the gate has already resolved to “not installed”, so your bridge, settings, and render hooks were never registered and every registration assertion fails. Put it in defineEnvironment() (or getEnvironmentSetUp()), as above. Capell’s own admin test case does exactly this.

ExtensionTestHarness::markPackageInstalled() is the supported way to simulate an installed package in tests and is part of the stable ExtensionTestHarness surface. CapellCore::forcePackageInstalled() underneath it is @internal; do not call it from package tests.

Testbench has no manifest discovery, so nothing reads your capell.json settings entry and app(YourSettings::class) stays unbound even after markPackageInstalled(). SettingsBootstrapper builds config('settings.settings') from each registered package’s setting property, with no install-state check.

The reliable route is to override packageSettingClass() on your provider, which AbstractPackageServiceProvider reads while registering package metadata:

protected function packageSettingClass(): ?string
{
return AnnouncementBarSettings::class;
}

That works in tests and in a real application, and keeps the manifest entry as the declaration of record.

Add the providers for the surfaces your package uses:

Your packageAlso register
Registers render hooks or renders public HTMLCapell\Frontend\Providers\FrontendServiceProvider
Registers admin pages, resources, or widgetsCapell\Admin\Providers\AdminServiceProvider, the Filament set (FilamentServiceProvider, FormsServiceProvider, SchemasServiceProvider, SupportServiceProvider, TablesServiceProvider, WidgetsServiceProvider, ActionsServiceProvider, NotificationsServiceProvider), plus Livewire\LivewireServiceProvider and a Filament panel provider

RenderHookRegistry is bound by the frontend provider, so a package that calls app(RenderHookRegistry::class) during boot fails without it.

Register the frontend provider and mark the extension installed in the base TestCase::defineEnvironment() shown above. The provider registers its hook during bootstrap. Assert on the registry once the application has booted:

use Capell\Frontend\Enums\RenderHookLocation;
use Capell\Frontend\Support\Render\RenderHookRegistry;
it('registers the announcement render hook', function (): void {
expect(resolve(RenderHookRegistry::class)->get(RenderHookLocation::HeaderAfter))
->not->toBeEmpty();
});

For an HTTP test that renders $this->get('/'), seed a site, language, and published page so the request has a frontend route to render.

Spatie settings need their migration applied before the group hydrates, or every property read throws.

Add a migratePackageSettings() helper to the base TestCase. It creates Spatie’s settings table first, then runs the package’s settings migrations, and a test that reads settings calls it before the first read:

use ReflectionClass;
use Spatie\LaravelSettings\LaravelSettingsServiceProvider;
/** Create Spatie's settings table, then apply this package's settings migrations. */
protected function migratePackageSettings(): void
{
$settingsTable = dirname((string) new ReflectionClass(LaravelSettingsServiceProvider::class)->getFileName(), 2)
. '/database/migrations/create_settings_table.php.stub';
(require $settingsTable)->up();
foreach (glob(dirname(__DIR__) . '/database/settings/*.php') ?: [] as $settingsMigration) {
(require $settingsMigration)->up();
}
}

dirname(__DIR__) is the package root, so /database/settings is the package’s own settings directory; get the depth wrong and glob() returns an empty array, the loop silently does nothing, and every settings property read then throws. The capell:make:extension scaffold generates the same helper in its tests/TestCase.php.

<?php
declare(strict_types=1);
use Acme\AnnouncementBar\Tests\TestCase;
pest()->extend(TestCase::class)->in('Feature', 'Unit');

Then run the suite from the package root:

Terminal window
vendor/bin/pest

ExtensionTestHarness is a stable surface that checks the manifest and the runtime wiring Capell relies on. Point it at the package root once, then chain only the assertions the package needs:

use Capell\Core\Enums\RuntimeRole;
use Capell\Core\Testing\ExtensionTestHarness;
it('declares a manifest Capell accepts', function (): void {
ExtensionTestHarness::forPath(dirname(__DIR__, 2))->assertManifestValid();
});
it('declares the contributions the package ships', function (): void {
ExtensionTestHarness::forPath(dirname(__DIR__, 2))
->assertContributionRegistered('setting', AnnouncementBarSettings::class)
->assertRoutesOwnedByPackage()
->assertScheduledJobsRegistered();
});
it('declares nothing that is unsafe to cache publicly', function (): void {
ExtensionTestHarness::forPath(dirname(__DIR__, 2))->assertNoUnsafePublicCache();
});
it('boots its providers for the authoring runtime role', function (): void {
$providers = ExtensionTestHarness::forPath(dirname(__DIR__, 2))->bootProviders(app(), RuntimeRole::Authoring);
expect($providers)->toContain(AnnouncementBarServiceProvider::class);
});
it('declares a theme manifest the theme loader accepts', function (): void {
ExtensionTestHarness::forPath(dirname(__DIR__, 2))
->assertThemeManifest()
->assertThemeUsesSafeAssetUrls();
});

The harness throws an AssertionError on the first failure instead of recording PHPUnit assertions, so a test that only calls it is reported as risky and fails under --fail-on-risky. End such a test with $this->addToAssertionCount(1);, as the generated tests do. Do not wrap the call in expect(fn () => ...)->not->toThrow(Throwable::class): Pest treats an interface name as expected message text, so that expectation passes even when the harness throws.

  • assertManifestValid() runs the same validator as capell:extension-audit and Marketplace submission, and fails with the first problem.
  • assertContributionRegistered($type, $class) fails when capell.json does not declare that contribution.
  • assertRoutesOwnedByPackage() fails when a route contribution has no namePrefix, and assertScheduledJobsRegistered() fails when a scheduled job has no schedule.
  • assertNoUnsafePublicCache() fails when the cache safety metadata would let private output into the public cache.
  • bootProviders($app, $role) registers the package through the production provider loader for a runtime role, so provider isolation and boot behaviour are tested, not only metadata.
  • assertThemeManifest() and assertThemeUsesSafeAssetUrls() are for theme packages.

Every Capell package runs the companion package contract. Build the contract from the package’s own files and run it:

use Capell\Core\Testing\Data\CompanionPackageContractData;
use Capell\Core\Testing\ExtensionTestHarness;
it('meets the companion package contract', function (): void {
ExtensionTestHarness::assertCompanionPackageContract(
CompanionPackageContractData::forPackage(dirname(__DIR__, 2)),
);
// The contract suite throws on the first failed check, so reaching this line means every check passed.
$this->addToAssertionCount(1);
});

capell:make:extension generates this test as tests/Feature/PackageContractTest.php in both profiles, so a new package runs the contract from its first composer test.

forPackage() reads capell.json, the first runtime provider (or the first metadata provider) and every migration under database/migrations. Pass authorizationAssertion, cacheInvalidationAssertion, lifecycleAssertion or publicRender closures to exercise the package’s own behaviour as well.

Each failure starts with a check ID in brackets. These checks always run:

  • [manifest.valid], [provider.boot] and [migration.discovery].
  • [security.throttles]: declared throttles match the registered routes.
  • [security.outbound-http]: every class in src that opens an outbound connection is listed in security.externalHttpClients.clients, and every listed class still opens one. An SDK that wraps its own transport goes in manualClients. A stream read whose target is neither a URL nor evidently local needs // capell-security-scan: local-stream <reason> or // capell-security-scan: remote-stream <reason> on the line before it. Every statement that builds a request through the Http facade must set a total timeout, with timeout() or a 'timeout' request option. For an address that comes from configuration, content or a user, use OutboundHttp::guarded(); OutboundHttpPolicy::configuredEndpoint($url) is the policy for an operator-configured endpoint that receives a token or instance credentials (https only, no redirects). Guarded requests resolve DNS through ResolvesHostAddresses, so a test that fakes the HTTP client binds Capell\Core\Testing\Http\FakeHostAddressResolver::bind() to answer lookups without the network.
  • [public-output.views]: public Blade views hold no authoring markers, signed editor URLs, record keys, secrets, queries or cache access. Views under filament, admin, editor, frontend-authoring, screenshots and mail directories are not public, so keep admin views there.
  • [privacy.personal-data]: a package whose migrations create a personal-data column (email, phone, IP address, user agent, names, date of birth, postcode and their hashed forms) registers both a Core privacy subject exporter and eraser, so a privacy request finds and removes that data. Registering only one side fails too.

A package opts out of security.throttles, security.outbound-http, public-output.views or privacy.personal-data only with a decision record at docs/decisions/contract-opt-out-<check id>.md. The record needs a ## Decision and a ## Reason section, each with text. An incomplete record, or a record for any other check, fails with [contract.opt-out].

What is not available outside the monorepo

Section titled “What is not available outside the monorepo”

Capell’s internal test helpers live under the Capell\Tests\ namespace, which is mapped in this repository’s autoload-dev only. CreatesAdminUser, TestingFrontend, IsolatedTestbenchSkeleton, PackageTestDatabaseGuard, and the Capell\Tests\Support\Fakes\* doubles are not shipped to third-party packages. Do not reference them; write the equivalent fixture in your own package.

CapellCore::registerManifestPackage(), CapellCore::getMigrations(), and CapellCore::getSettingMigrations() are shipped API and safe to use. ExtensionTestHarness::markPackageInstalled() is the supported way to simulate an installed package, as noted above.

Changes to the capell:make:extension stubs are checked against real consumers, not only file shape. From this repository, with a Capell Packages checkout that provides Layout Builder and the default theme:

Terminal window
CAPELL_PACKAGES_CHECKOUT=/path/to/capell-packages bash scripts/verify-generated-extension-consumer.sh

The script generates both profiles and runs each generated suite with composer install and composer test -- --fail-on-risky. It then creates a fresh Laravel application, installs Capell unattended and follows the full profile’s generated README. It also requires clean capell:package:lint and capell:extension-audit results, and saves and reloads public_label through Extensions management. Finally, it checks the widget’s editor block, assets and escaped public output while the package is enabled, disabled and enabled again. Set CAPELL_GENERATED_CONSUMER_ROOT to keep the consumer for inspection. Composer needs network access.

Continuous integration for an extension repository

Section titled “Continuous integration for an extension repository”

Save this as .github/workflows/tests.yml in the package repository. It installs dependencies from Packagist and runs the generated Pest suite on PHP 8.4 against the newest Capell Core release your constraint allows.

name: Tests
on:
push:
branches: [main]
pull_request:
jobs:
pest:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: ['8.4']
capell-core: ['^1.0']
dependencies: [highest]
name: PHP ${{ matrix.php }}, capell-app/core ${{ matrix.capell-core }} (${{ matrix.dependencies }})
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: pdo_sqlite, intl, gd
coverage: none
- name: Pin the Capell Core range
run: composer require "capell-app/core:${{ matrix.capell-core }}" --no-update --no-interaction
- name: Install dependencies
run: composer update --prefer-dist --no-interaction --no-progress ${{ matrix.dependencies == 'lowest' && '--prefer-lowest' || '' }}
- name: Run tests
run: composer test -- --fail-on-risky

To prove the package still works on the oldest Core release it claims to support, raise the capell-app/core floor in composer.json to that release and add lowest to dependencies. The scaffold writes ^1.0, whose floor predates parts of the test harness, so a lowest run fails until you raise it. To test specific Core lines as well, add them to capell-core with Composer constraint syntax, for example ['~1.0.78', '^1.0']. Keep each entry inside the range your composer.json declares, or Composer refuses to resolve it. The generated phpunit.xml.dist already uses SQLite in memory, so the job needs no database service. A full-profile package resolves capell-app/admin, capell-app/frontend and capell-app/layout-builder from Packagist in the same way.

Create a package test case that registers only the providers the package needs.

protected function getPackageProviders($app): array
{
return [
\Capell\Core\Providers\CapellServiceProvider::class,
\Capell\Admin\Providers\AdminServiceProvider::class,
\Capell\Example\Providers\ExampleServiceProvider::class,
\Capell\Example\Providers\AdminServiceProvider::class,
];
}

For installed-only behaviour, call ExtensionTestHarness::markPackageInstalled('capell-app/example') from TestCase::defineEnvironment() before the package provider boots.

Every package with capell.json should test that required manifest fields exist and providers are loadable.

Provider tests should assert:

  • package metadata is registered.
  • admin pages are registered through CapellAdmin.
  • dashboard Filament widgets are registered in the correct dashboard slot.
  • settings schemas are registered when present.
it('registers package metadata', function (): void {
$package = CapellCore::getPackage('capell-app/example');
expect($package->name)->toBe('capell-app/example');
});

Test Actions directly. Avoid HTTP tests unless the route or Filament page behaviour is the subject.

it('builds the package output data', function (): void {
$data = BuildExampleOutputAction::run($input);
expect($data)->toBeInstanceOf(ExampleOutputData::class);
});

Test direct registration first, then add one render test for the user-facing surface.

it('tags the page schema extender', function (): void {
$extenders = collect(app()->tagged(PageSchemaExtender::TAG));
expect($extenders)
->toContain(fn (PageSchemaExtender $extender): bool => $extender instanceof ExamplePageSchemaExtender);
});
it('registers an extension settings page', function (): void {
ExtensionTestHarness::markPackageInstalled('capell-app/example');
expect(resolve(ExtensionPageRegistry::class)->get('capell-app/example'))
->toBe(ExampleSettingsPage::class);
});

Any package that renders public HTML needs presence and absence assertions.

it('renders public package output without authoring state', function (): void {
$response = $this->get('/example-page');
$response->assertOk();
expect($response->getContent())
->toContain('Expected public copy')
->not->toContain('data-capell-editor')
->not->toContain('field_path')
->not->toContain('signed');
});

Run Blade view coverage when adding or changing package views:

Terminal window
composer coverage:blade

The check is ratcheted by tests/BladeCoverage/baseline.json and only counts views Laravel actually renders. See Blade view coverage. coverage:blade is a monorepo Composer script; a standalone package uses its own coverage configuration instead.

Marketplace-adjacent packages should prove local compatibility and authorisation state handling without treating remote metadata as trusted code.

it('records install intent only when an instance is connected', function (): void {
MarketplaceInstance::factory()->create();
$acquisition = CreateExtensionAcquisitionAction::run($listing);
expect($acquisition->composerCommand)->toContain('composer require');
});

Use arch tests to prevent package boundary regressions:

  • package code should not import app-specific classes.
  • frontend providers should not import Filament.
  • admin providers should not run on frontend-only contexts.
  • packages should not import sibling packages unless Composer requires them.

From a standalone package repository, run your own suite:

Terminal window
vendor/bin/pest

Inside this monorepo, run the package suite against the root configuration during implementation:

Terminal window
vendor/bin/pest packages/example/tests --configuration=phpunit.xml

Run the host suite only when the package touches shared contracts, public rendering, install/upgrade, or admin boot:

Terminal window
composer test

Tests pin observable outcomes only: return values, persisted state, rendered output, dispatched events, HTTP responses. The logic underneath can then change freely while its output stays the same, and a refactor that keeps output identical must never turn a test red.

Do not assert internals:

  • private or protected members, call order, mock call counts and shouldReceive choreography (unless the call itself is the contract), class or method names, container wiring;
  • file contents, line numbers or offsets, commit SHAs in permalinks, exact formatted source snippets, greps over source structure.

Rules that follow:

  • Prefer real objects and fakes at boundaries over mocks. Use the narrowest outcome assertion that proves the behaviour.
  • Every test justifies the user-visible or API-visible behaviour it protects. Fewer, faster, outcome-level tests beat many coupled ones.
  • Heavy per-test setup and slow fixtures are defects: use in-memory SQLite, factories and shared minimal fixtures, and no network or Docker in unit tests.
  • Derive expected values from the source of truth instead of restating them. A second hand-kept copy goes stale and fails far from its cause.
  • When a check must read a file (a docs-to-source contract, a manifest), assert the narrowest token that encodes the contract, with a comment stating the behaviour it protects. Never read “line N” and expect text.
  • Prove a new guard fails against the broken state and passes with the fix.

Refactor test: would this test fail if I rewrote the implementation with identical output? If yes, rewrite it. It must also survive reformatting, reordering, added blank lines and unrelated refactors.

Before and after, from tests/Unit/ExtensionSurfaceCatalogContractTest.php. The documentation links to test files through permalinks. The old test read the anchored line and expected the section text on it, so inserting one line above a test turned it red although nothing was wrong:

// Before: position-coupled.
$line = (int) ltrim((string) parse_url($reference, PHP_URL_FRAGMENT), 'L');
$source = file($path, FILE_IGNORE_NEW_LINES);
expect($source[$line - 1])->toContain($expectedSection);
// After: the referenced file exists and still contains the named section, wherever it sits.
expect($root . '/' . $path)->toBeFile()
->and((string) file_get_contents($root . '/' . $path))->toContain($expectedSection);

packages/core/tests/Arch/TestsAssertNoSourcePositionsTest.php fails when a test pins a 40-character blob permalink to a line anchor or indexes source lines by number.