-
-
Save rizkhal/3dd3b8e674f706032c075cd4dc66cd91 to your computer and use it in GitHub Desktop.
A simple way of testing that your Laravel commands are scheduled exactly when and how you expect. This approach does not trigger commands to actually execute, which is what a lot of other suggestions do.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\Console\Kernel; | |
use Carbon\Carbon; | |
use Illuminate\Console\Scheduling\Event; | |
use Illuminate\Console\Scheduling\Schedule; | |
use Illuminate\Support\Collection; | |
class ConsoleSchedulingTest extends TestCase | |
{ | |
/** | |
* Verify that my-command-name is scheduled to run at 7AM ET in production. | |
*/ | |
public function testCommandIsScheduledToRunAt7am() { | |
$date = Carbon::today()->timezone('America/Toronto')->setTime(7,0); | |
$dueEvents = $this->getScheduledEventsForCommand('my-command-name', $date); | |
$this->assertCount(1, $dueEvents, 'Command is not scheduled for expected time'); | |
/** | |
* @var \Illuminate\Console\Scheduling\Event $event | |
*/ | |
$event = $dueEvents->first(); | |
$this->assertTrue($event->runsInEnvironment('production')); | |
} | |
/** | |
* For scheduled jobs, the fully qualified class name should be referenced. | |
*/ | |
public function testJobIsScheduled() { | |
$scheduledJobEvents = $this->getScheduledEventsForCommand(MyJob::class); | |
$this->assertCount(1, $scheduledJobEvents); | |
} | |
/** | |
* @param string $commandName | |
* @param Carbon|null $atTime | |
* @return Collection | |
*/ | |
private function getScheduledEventsForCommand(string $commandName, Carbon $atTime=null): Collection { | |
# configure scheduled through Kernel | |
new Kernel($this->app); | |
/** | |
* @var Schedule $schedule | |
*/ | |
$schedule = $this->app->get(Schedule::class); | |
return collect($schedule->events())->filter(function(ScheduleEvent $event) use($commandName, $atTime){ | |
if(!str_contains($event->command, $commandName) && strcmp($event->description, $commandName) !== 0) { | |
return false; | |
} | |
# optionally filter out events that are not due at the given time. | |
if($atTime !== null) { | |
Carbon::setTestNow($atTime); | |
return $event->isDue($this->app); | |
} else { | |
return true; | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment