Yes, you can set a global variable to determine if you are running tests or not. In Laravel, you can use environment variables to achieve this. You can set an environment variable in your phpunit.xml file, which is used when running tests.
Here’s how you can do it:
-
Set the Environment Variable in
phpunit.xml:Open your
phpunit.xmlfile and add an environment variable to indicate that you are running tests.<php> <env name="IS_TESTING" value="true"/> </php> -
Access the Environment Variable in Your Seeder:
In your seeder files, you can check the value of this environment variable using Laravel's
envhelper function.if (env('IS_TESTING')) { User::factory()->count(20)->create()->each(function($user) { $tasks = [ SaveUserRoleRole::class, SavePresentation::class ]; foreach ($tasks as $task) { (new $task)->handle($user); } }); } else { User::factory()->count(20)->create()->each(function($user) { $tasks = [ SaveUserRoleRole::class, CreateFolder::class, SavePresentation::class, CreateImage::class ]; foreach ($tasks as $task) { (new $task)->handle($user); } }); } -
Ensure Environment Variable is Available Globally:
To make sure the environment variable is available globally, you can set it in your
AppServiceProvideror any other service provider that is loaded early in the request lifecycle.// In AppServiceProvider or any other service provider public function boot() { if (env('IS_TESTING')) { define('IS_TESTING', true); } else { define('IS_TESTING', false); } }With this setup, you can use the
IS_TESTINGconstant anywhere in your application to check if you are running tests. -
Using the Constant in Your Seeder:
Now, you can use the
IS_TESTINGconstant in your seeder files.if (IS_TESTING) { User::factory()->count(20)->create()->each(function($user) { $tasks = [ SaveUserRoleRole::class, SavePresentation::class ]; foreach ($tasks as $task) { (new $task)->handle($user); } }); } else { User::factory()->count(20)->create()->each(function($user) { $tasks = [ SaveUserRoleRole::class, CreateFolder::class, SavePresentation::class, CreateImage::class ]; foreach ($tasks as $task) { (new $task)->handle($user); } }); }
By following these steps, you can set a global variable to determine if you are running tests and use it in your seeder files to conditionally execute different logic.