Laravel makes rate limiting easy to set up, so it's easy to overlook that this is a critical piece of business logic that needs tests.
But what kind of tests? Should we set a rate limit for 60 requests, then send 61 requests and check for a 429 response? Then travel forward a minute and check that the limit resets?
I wouldn't write those kinds of tests.
That's the built-in functionality from the ThrottleRequests middleware, and Laravel's own test suite should already cover that.
The key things worth testing are the decisions you made for your application.
First, is the limiter attached to the right route? A forgotten middleware is easy to miss in code review, and a quick smoke test catches it. Laravel adds rate limit headers to every throttled response, so you don't need to hit the limit to see it.
public function testLoginIsRateLimited(): void
{
$this->post(route('login'), ['email' => '[email protected]'])
->assertHeader('X-RateLimit-Limit', '5');
}
Second, what are you limiting by?
The key you pass to by() is your business logic, and it's easy to get wrong.
RateLimiter::for('login', fn(Request $request) => Limit::perMinute(5)->by($request->input('email')));
If one user hits the limit, a different user should still be able to log in.
public function testLoginLimitIsPerEmail(): void
{
for ($i = 0; $i < 5; $i++) {
$this->post(route('login'), ['email' => '[email protected]']);
}
$this->post(route('login'), ['email' => '[email protected]'])
->assertTooManyRequests();
$this->post(route('login'), ['email' => '[email protected]'])
->assertRedirect();
}
Yes, this test does check for a 429. But it's there to prove Alice actually hit the limit. Without it, Bob's request would pass even if the limiter were global, or missing entirely.
The same goes for anything else you add, like a custom response or an after() callback that only counts certain requests.
If you wrote the logic, test it.
But if Laravel wrote it, I think it's safe to trust it's covered elsewhere.
Here to help,
Joel
P.S. Our testing course is full of decisions like this one, about what to test in your own code and what to trust the framework with.