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

Pest Plugin Inside Laravel Package

faissaloux/pest-plugin-inside

Pest plugin to run tests from inside your app’s context. Provides helpers to bootstrap Laravel or other frameworks for faster, cleaner integration-style tests without leaving Pest. Simple setup, lightweight, and aimed at improving developer ergonomics.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev faissaloux/pest-plugin-inside
    

    Ensure your pest.php config includes the plugin:

    plugins([
        PestPluginInside::class,
    ]);
    
  2. First Use Case: Validate a PHP file’s returned array meets specific criteria (e.g., lowercase keys/values):

    // tests/Feature/ExampleTest.php
    use function PestPluginInside\expect;
    
    it('ensures file content is lowercase')->expect('config/strings.php')->toReturnLowercase();
    
  3. Key Files to Reference:

    • pest.php (plugin registration)
    • Test files (e.g., tests/Feature/ValidationTest.php) for assertions.

Implementation Patterns

Core Workflows

  1. File-Level Assertions:

    // Validate a single file
    expect('app/Constants.php')->toReturnUnique();
    
  2. Directory Scanning:

    // Scan all PHP files recursively
    expect('config')->toReturnStrings();
    
    // Limit scan depth (e.g., only immediate files)
    expect('config')->toReturnStrings(depth: 0);
    
  3. Combined Validations:

    expect('data/translations.php')
        ->toReturnLowercase()
        ->toBeOrdered()
        ->forbidEmpty();
    
  4. Text File Support:

    // Validate a .txt file (e.g., logs, stubs)
    expect('stubs/response.txt')->toReturnSingleWords();
    

Integration Tips

  • Laravel-Specific: Use with config/, resources/, or database/seeds/ files to enforce consistency:

    expect('config/lang.php')->toReturnStrings();
    
  • CI/CD: Add to test suites to fail builds on non-compliant files:

    # .github/workflows/tests.yml
    - run: php artisan test --filter="file validation"
    
  • Custom Helpers: Extend assertions in PestPluginInside via traits or custom macros:

    // tests/TestCase.php
    use function PestPluginInside\expect;
    
    beforeEach(function () {
        expect('app/Helpers/')->toReturnSingleWords();
    });
    

Gotchas and Tips

Pitfalls

  1. File Paths:

    • Use relative paths from the project root (e.g., app/Constants.php).
    • Absolute paths (e.g., /var/www/app/Constants.php) fail silently.
  2. Case Sensitivity:

    • toReturnLowercase() fails on mixed-case strings (e.g., "CaSe"). Use strtolower() in files if needed.
  3. Nested Arrays:

    • toReturnUnique() checks all levels of nested arrays. Flatten data if needed:
      // config/arrays.php
      return ['a' => ['b', 'b']]; // Fails uniqueness
      
  4. Windows Line Endings:

    • Text files (*.txt) may fail on \r\n. Normalize with:
      str_replace(["\r\n", "\r"], "\n", file_get_contents($file));
      
  5. Depth Parameter:

    • depth: 0 scans only the target directory (no subdirectories). Omit or use null for full recursion.

Debugging

  • Verbose Failures: The plugin highlights the exact line/file causing failures (e.g., "Expected 'CaSe' to be lowercase").

  • Custom Error Messages: Override defaults with expect()->customMessage():

    expect('app/Enums.php')->toReturnUnique()->customMessage('All enum values must be unique.');
    

Extension Points

  1. Add Custom Assertions: Extend the plugin by creating a new Investigator class:

    // app/Plugins/Pest/Investigators/CustomInvestigator.php
    namespace App\Plugins\Pest\Investigators;
    
    use PestPluginInside\Investigator;
    
    class CustomInvestigator extends Investigator
    {
        public function toContainOnlyLetters(): void
        {
            $this->assertAllStringsMatch('/^[a-zA-Z]+$/');
        }
    }
    

    Register in pest.php:

    plugins([
        PestPluginInside::class,
        \App\Plugins\Pest\Investigators\CustomInvestigator::class,
    ]);
    
  2. Mock File Content: For isolated tests, mock file_get_contents():

    beforeEach(function () {
        $this->mock(File::class)
            ->shouldReceive('get')
            ->with('config/test.php')
            ->andReturn('["mocked", "data"]');
    });
    
  3. Performance:

    • Cache results for large directories by storing parsed files in storage/:
      // app/Providers/AppServiceProvider.php
      use Illuminate\Support\Facades\File;
      
      public function boot()
      {
          File::ensureDirectoryExists(storage_path('pest-cache'));
      }
      
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui