Snapey's avatar
Level 122

Calling application more than once in a test

I was reading @sinnbeck advice on testing rate limiting

https://sinnbeck.dev/posts/rate-limiting-routes-in-laravel-with-tests

But came across this note in the Laravel docs;

In general, each of your tests should only make one request to your application. Unexpected behavior may occur if multiple requests are executed within a single test method.

https://laravel.com/docs/11.x/http-tests#making-requests

In testing rate limiting, I am hitting the endpoint multiple times and checking if the user sees a limiter message and that their account is locked. But the note in the docs gave me pause...

0 likes
2 replies
LaryAI's avatar
Level 58

When testing rate limiting in Laravel, it's common to make multiple requests to an endpoint to ensure that the rate limiting functionality works as expected. While the Laravel documentation advises that each test should generally make only one request to avoid unexpected behavior, there are scenarios where making multiple requests within a single test is necessary and acceptable, such as testing rate limiting.

Here's a solution to test rate limiting in Laravel while ensuring that your tests remain reliable and maintainable:

  1. Use a fresh application instance for each request: This can be achieved by using the refreshApplication method to reset the application state between requests.

  2. Leverage data providers: If you need to test multiple scenarios, consider using PHPUnit's data providers to keep your tests clean and organized.

Here's an example of how you can test rate limiting by making multiple requests within a single test method:

In this example:

  • We use the RateLimiter facade to clear any existing rate limiter data before starting the test.
  • We make multiple requests to the endpoint within a loop.
  • We assert that the initial requests are successful (status 200).
  • We then make an additional request and assert that it is rate limited (status 429).

By using the RateLimiter::clear method, we ensure that the rate limiter state is reset before the test runs, which helps avoid any unexpected behavior due to leftover state from previous tests.

This approach allows you to test rate limiting effectively while adhering to best practices for maintaining test reliability.

vincent15000's avatar

According to me, in this case, it's not a problem to make several requests in the same test, because this test needs that you make several requests and they are the same requests.

But in other cases, if you need to make 2 different requests (ie not the same), it's better to do 2 different tests.

I think that some different requests can intefere with each other in any way (events, database, ...), whereas same requests won't disturb self, thus triggering unexpected behavior.

Not sure to explain really well what I'm thinking ...

Please or to participate in this conversation.