Detecting when Laravel Dusk is running

139 Views Asked by At

Often in Laravel I need to detect the environment to avoid triggering certain code while running tests, like logging or sending an email:

if (!app()->environment("testing")) {
    Mail::to($email)->queue(new WelcomeEmail($transaction->id));
}

This works fine when the environment is set to testing in 3 of my 4 environment files (local and CI/CD unit tests, Dusk on CI/CD), but my .env.dusk.local file - which I need to run Laravel Dusk locally - has a local environment, and in these cases Dusk triggers the sending of emails, logs, etc.

The cleanest solution I can see for this would be to detect whether Dusk is running in any environment - I'm aware there's an app()->runningUnitTests() method, but don't know of an equivalent for Dusk.

2

There are 2 best solutions below

0
On BEST ANSWER

Dusk will check for a file .env.dusk.<environment>.

Using local environment as an example, it will check .env.dusk.local. Setting APP_ENV=dusk in that file will permit you to add checks like if(app()->environment('dusk')) where necessary.

As noted in the comments, though, for the specific example of sending mail or logging, you're generally better off overriding MAIL_DRIVER or LOG_CHANNEL to something suitable for testing, like MAIL_DRIVER=log or LOG_CHANNEL=daily, so you can still test that functionality without sending actual emails.

2
On

As an addendum to ceejayoz's answer and to explicitly spell out what I did to solve this, I changed the environment variables in both my env.dusk.local (for running Dusk locally) and .env.dusk.testing (for running Dusk in CI/CD) to:

APP_ENV=dusk

This overrides the environment variable in .env and allows me to do:

if (!app()->environment("testing", "dusk")) { // if not running unit/feature or Dusk tests
    Mail::to($email)->queue(new WelcomeEmail($transaction->id));
}