Test that a laravel command is scheduled
If you have a Laravel application that schedules commands to run at specific times using the app/Console/Kernel.php
file, you may want to add a test that ensures that the scheduled command is running correctly.
First, create a new test file in the tests directory of your Laravel application. In this example, we'll call the file KernelTest.php and the purpose is to test that the inspire
command is scheduled to run every hour.
Note: For the example I am using the phppest syntax but you should be able to adapt the code in case you use the built-in syntax:
use Illuminate\Console\Scheduling\Event;
use Illuminate\Console\Scheduling\Schedule;
it('schedules the `inspire` command correctly', function () {
$schedule = app()->make(Schedule::class);
$events = collect($schedule->events())->filter(function (Event $event) {
return stripos($event->command, 'inspire');
});
if ($events->count() == 0) {
$this->fail('No events found');
}
$events->each(function (Event $event) {
$this->assertEquals('0 * * * *', $event->expression);
});
});
In this test, we first get an instance of the Schedule class using the app function. We then use the events method to get an array of all scheduled events.
We then use the filter method to find any events that have the command property containing the word 'inspire'. If no events are found, we fail the test.
If one or more events are found, we use the each method to loop through each event and assert that the expression property is set to '0 * * * *'
, which indicates that the command is scheduled to run every hour.
To run the test, use the following command:
php artisan test --filter KernelTest
This test should pass if the inspire command is scheduled to run every hour in the Kernel class.
That's it! You now have a test to ensure that your scheduled commands are running correctly in your Laravel application.