Laravel how to set app environment during tests

David Carr

Laravel Framework Tests

If you need to set an environment to be a specific one such as staging you can override the environment by changing the config value app_env

config(['app.env' => 'staging']);

Then doing a dd on config(‘app.env’) will return that environment you’ve just set.

I haven’t found a way to set environments with app()->environment() so instead, I recommend using this in_array function and passing in the config(‘app.env’) and then specifically defining the environments. 

in_array(config('app.env'), ['local', 'staging'])

For example, say you have this in a command:

if (! in_array(config('app.env'), ['local', 'staging'])) {
    $this->error(‘Will only run on local and staging environments’);
    return true;
}

Test this runs when the environment is set to production

test(‘cannot run on production’, function () {

    config(['app.env' => 'production']);

    $this->artisan('db:production-sync')
        ->expectsOutput(‘DB sync will only run on local and staging environments’)
        ->assertExitCode(true);
});

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.