Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 67 ยท Testing

Browser Tests, Static Analysis and Code Style

Go beyond feature tests with Pest browser testing, Larastan static analysis, Pint code style, Rector upgrades and a GitHub Actions CI pipeline.

Feature tests check that your application behaves correctly. A healthy project also needs checks that feature tests cannot give you: does the JavaScript actually work in a real browser, are there type mistakes hiding in rarely run code, and does everyone on the team format code the same way? Each question has a tool, and together they run automatically on every push.

This lesson tours the four tools most Laravel teams use: Pest browser testing, Larastan, Laravel Pint and Rector, and shows how to run them in CI with GitHub Actions. Installing and configuring them is read-only here, since the site cannot run Composer or a browser. The runnable example is a small style-rule checker that shows what a tool like Pint does at its core.

Where each tool fits

flowchart LR
    C["Code change"] --> P["Pint: style"]
    P --> L["Larastan: types"]
    L --> T["Pest: unit and feature tests"]
    T --> B["Pest browser tests"]
    B --> OK["Merge"]

Cheap, fast checks run first. Slower checks run only if the earlier ones pass.

Tool Question it answers Speed
Pint Is the code formatted consistently? Seconds
Larastan Are there type errors or impossible calls? Seconds to a minute
Pest (unit/feature) Does the logic behave? Seconds to minutes
Pest browser Does the real UI work in a browser? Slowest
Rector Can code be upgraded or refactored automatically? On demand

Laravel Pint: code style

Pint is Laravel's opinionated code formatter, built on PHP-CS-Fixer. It ships with new Laravel projects, and its default laravel preset needs no configuration:

Terminal
vendor/bin/pint                 # fix every file
vendor/bin/pint --dirty         # only files changed in git
vendor/bin/pint --test          # report problems, change nothing (for CI)

To tune rules, add a pint.json in the project root:

JSON
{
    "preset": "laravel",
    "rules": {
        "declare_strict_types": true,
        "ordered_imports": { "sort_algorithm": "alpha" }
    }
}

The point of a formatter is to end style arguments. Reviewers stop commenting on spacing and quotes, and diffs only show real changes. Run Pint before every commit, ideally from an editor action or a git hook.

Larastan: static analysis

PHPStan reads your code without running it and reports type errors: calling a method that does not exist, passing a string where an int is required, reading a property on a value that may be null. Larastan is the Laravel extension that teaches PHPStan about Eloquent magic, facades, collections and relationships, so it understands $user->posts and Post::query().

Terminal
composer require --dev larastan/larastan

A minimal phpstan.neon:

TEXT
includes:
    - vendor/larastan/larastan/extension.neon

parameters:
    level: 5
    paths:
        - app
        - routes
Terminal
vendor/bin/phpstan analyse

Levels run from 0 (basic checks) to 10 (strictest). Start at a level your code already passes and raise it over time. If an old project has hundreds of errors, generate a baseline (--generate-baseline) so only new errors fail the build, then pay the old ones down gradually.

PHPDoc types help Larastan a lot. For example, tell it what a collection holds:

PHP
/** @return Collection<int, Post> */
public function recentPosts(): Collection
{
    return $this->posts()->latest()->take(5)->get();
}

Static analysis catches the bug in the branch your tests never reached. It does not replace tests, because it cannot know whether the logic is right, only whether the types fit.

Rector: automated refactoring

Rector applies code transformations: upgrade syntax to a newer PHP version, move to a new Laravel version's conventions, add return types, remove dead code. You describe the rule sets in rector.php and run:

Terminal
vendor/bin/rector process --dry-run   # show what would change
vendor/bin/rector process             # apply it

Always use --dry-run first and review the diff, then run your tests. Rector is a power tool for upgrades and large clean-ups, so you run it on demand, not on every commit. The community package driftingly/rector-laravel adds Laravel-specific rule sets.

Pest browser testing

Feature tests never run JavaScript. A browser test drives a real (headless) browser, clicks buttons, fills forms and checks the page after scripts have run. Pest's browser plugin gives it a short API, using Playwright underneath:

PHP
it('lets a user sign in', function () {
    $user = User::factory()->create(['password' => 'secret-pass-123']);

    $page = visit('/login');

    $page->fill('email', $user->email)
        ->fill('password', 'secret-pass-123')
        ->click('Log in')
        ->assertPathIs('/dashboard')
        ->assertSee('Welcome back')
        ->assertNoJavaScriptErrors();
});

Browser tests are the slowest and most fragile layer, so keep them for the journeys that matter most: sign-up, checkout, anything that depends on JavaScript such as a Livewire component or an Alpine dropdown. Test everything else with ordinary feature tests, which are far faster. Before using the plugin, check its current installation steps, since it needs Node and browser binaries on the machine.

Continuous integration with GitHub Actions

CI runs your checks on every push and pull request, on a clean machine, so "it works on my laptop" stops being an excuse. A typical workflow in .github/workflows/tests.yml:

YAML
name: tests

on: [push, pull_request]

jobs:
  ci:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.4'
          coverage: none

      - name: Install dependencies
        run: composer install --no-interaction --prefer-dist

      - name: Prepare environment
        run: |
          cp .env.example .env
          php artisan key:generate

      - name: Check style
        run: vendor/bin/pint --test

      - name: Static analysis
        run: vendor/bin/phpstan analyse --no-progress

      - name: Run tests
        run: php artisan test --compact

The order mirrors the diagram: cheap checks first, so a style mistake fails the job in seconds instead of after a ten-minute test run. Pin action versions and PHP versions, and cache Composer downloads once builds feel slow. Mark the workflow as required in your branch protection rules so a red build blocks merging.

A style-rule checker you can run

Pint is a rule engine at heart: read the code, apply rules, report what breaks. This stand-in checks four simple rules on a PHP snippet. It is not Pint, and it is far simpler than PHP-CS-Fixer, but it shows why such checks are fast, deterministic and easy to automate.

PHP A tiny style checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A real formatter goes one step further: instead of only reporting, it rewrites the code. The next example adds a "fixer" that repairs two of those rules automatically, which is what vendor/bin/pint does when you do not pass --test.

PHP From checker to fixer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line matters: a good fixer is idempotent, so running it twice changes nothing. That is why teams can run Pint freely without fear of churn.

A sensible routine

  1. Format on save or before commit: vendor/bin/pint --dirty.
  2. Run the tests that cover your change: php artisan test --compact --filter=....
  3. Let CI run the whole pipeline, including static analysis.
  4. Use Rector only for planned upgrades, in its own pull request.

None of these tools is magic. Static analysis misses logic bugs, a formatter cannot judge naming, and a browser test cannot cover every state. Together they remove whole classes of problems cheaply, which leaves your reviewers free to discuss design.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the purpose of vendor/bin/pint --test in CI?

    --test makes Pint report violations and exit with an error instead of fixing files, which is what a CI check needs.
  2. 2. What does Larastan add on top of PHPStan?

    Larastan is a PHPStan extension that understands Laravel's dynamic features, so analysis of models and relationships is accurate.
  3. 3. Why should browser tests be limited to important user journeys?

    Browser tests launch a real browser, which is slow and sensitive to timing. Faster feature tests should cover everything that does not need JavaScript.
  4. 4. How should you use Rector on an existing project?

    Rector changes code automatically, so preview the changes, apply them in a separate change and verify with your tests.

Summary

  • Pint formats code to a consistent style; use --test in CI and --dirty locally.
  • Larastan finds type errors without running code; start at a level you pass and raise it, using a baseline for old code.
  • Rector automates upgrades and refactors; preview with --dry-run.
  • Pest browser tests drive a real browser for the few journeys that depend on JavaScript.
  • GitHub Actions runs the checks on every push, cheap checks first.
  • The runnable examples are small stand-ins that show the idea behind a style checker and fixer.

Next: Security in Laravel