Summer Sale! All accounts are 50% off this week.

iambateman's avatar

Run Pest from Laravel command

I'm building an automated workflow that needs tests to run at the beginning of a command.

exec("./vendor/bin/pest", $result);
dd($result);

The code above works, but it just outputs a string of the results.

Is there a way to call Pest/PhpUnit programmatically to get structured results back? Ideally I'd like to get the equivalent of ["status"=>200] back to know that all the tests worked, or a list of the tests that failed.

0 likes
3 replies
martinbean's avatar
Level 80

@iambateman Just chain your command after the test command:

pest && your_command_here

Your command will only be ran if pest exits successfully.

1 like
iambateman's avatar

Thanks Martin! Based on this, I ended up with...

exec("./vendor/bin/pest && echo 'All successful'", $result);

if (str(implode($result))->endsWith('All successful')) {
        return $this->success = true;
}
...

Probably not going to win any code awards, but it works. Thanks!

thinkverse's avatar

Laravel has a helper class for running command processes that you can use, called Process.

use Illuminate\Support\Facades\Process;

$result = Process::path(base_path())
    ->env([
        'APP_ENV' => 'testing',
        'DB_CONNECTION' => 'sqlite',
        'DB_DATABASE' => ':memory:',
        'CACHE_DRIVER' => 'array',
    ])
    ->run('vendor/bin/pest --compact --bail');

if ($result->successful()) {
    return $result->output();
}

return $result->errorOutput();

This helps a lot when you need to set environment variables for the process.

Please or to participate in this conversation.