Laravel's Sleep Class
Laravel includes a Sleep class that wraps native sleep() and usleep(). Let's look at that feature.
Laravel 10.10 introduced a new feature to wrap PHP’s native sleep
and usleep
functions. Using this Sleep class means code that relies on sleep() doesn't need to sleep, which improves testing speed and still maintains confidence using the provided test helpers.
For example, imagine you have some code that needs to rely on sleep. Maybe you are doing an API call, and the endpoint has rate limiting. So you can’t just bombard them with hundreds of requests. One way around that might be to pause the execution after so many to stay outside their limit.
What becomes painful with this is now, if you have a unit test around this code, it will also have to call sleep and make your tests run super slow.
This is where Laravel’s Sleep class comes in. Change your call from PHP’s native sleep function to Laravel’s:
use Illuminate\Support\Sleep;
$waiting = true;
while ($waiting) {
Sleep::for(2)->seconds();
$waiting = /* ... */;
}
Then in your test, you can call Sleep::fake()
to stop it from actually pausing:
public function test_it_waits_until_ready()
{
Sleep::fake();
// ...
}
The official documentation details this feature and includes all the fluent methods you can use.