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
Answers
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:This overrides the environment variable in
.env
and allows me to do:Dusk will check for a file
.env.dusk.<environment>
.Using
local
environment as an example, it will check.env.dusk.local
. SettingAPP_ENV=dusk
in that file will permit you to add checks likeif(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
orLOG_CHANNEL
to something suitable for testing, likeMAIL_DRIVER=log
orLOG_CHANNEL=daily
, so you can still test that functionality without sending actual emails.