Is sleep in a test always bad?


Sometimes a test is flaky and a developer just slaps a sleep(3) in the middle of the test to make it pass, without really understanding why it's so sensitive to timing.

While I would avoid that behavior, there can be a valid use case for adding a sleep to a test. I recently ran into this while writing a test for a Stripe promotion code expiration.

Note: Our normal test suite never touches the actual Stripe API. It's mocked out. But we have a separate "external" test suite which communicates with the real API.

The Stripe API would not let me create a new promotion code with an expiration date in the past, so in order to test the expiration behavior, I had to create a code that expired 2 seconds from now, make my test wait 3 seconds, and then continue on with the logic in the test.

When using a non-standard technique this, adding a comment explaining why is critical. This will not only make it easier to pass code review, it will prevent some future developer from copying this behavior without understanding why it's there.

Here to help,


P.S. If you're ever feeling stuck in your Laravel app, we can help!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.