Freeze time in rate limit specs, to fix a flaky test #40
Loading…
Reference in a new issue
No description provided.
Delete branch "armin-bot/impress:claude/freeze-time-rate-limit-specs"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Fixes a flaky test in
spec/requests/rate_limits_spec.rb. It failed in run 59, on a PR that had nothing to do with rate limits.Cause
Rack::Attack counts requests in fixed time windows, not sliding ones: each counter's cache key includes
Time.now.to_i / period. So the 5-minutelogins/ipcounter resets every time the clock reaches a multiple of 5 minutes.In that run, "limits attempts from one IP, even against different accounts" made its 30 failed logins between
20:44:59.6and20:45:00.17. That's about 28 before the 20:45:00 boundary and 2 after. So when the final login with the correct password arrived, the new window's count was only 2. The login succeeded and redirected to/, instead of being throttled.Every throttle test in this file can hit this. The
pets/iptests are the most exposed, because that window is only 30 seconds.Fix
The fix freezes time around each example (with
ActiveSupport::Testing::TimeHelpers, asauthenticated_at_spec.rbalready does). That way all of a test's requests land in the same window. Theretry-aftertest still works, because it computes its value from the same frozen clock.Testing
bundle exec rspec spec/requests/rate_limits_spec.rb: 17 examples, 0 failures.I didn't add a test that recreates the boundary crossing, because the run 59 log already shows what happened.
🤖 Generated with Claude Code
https://claude.ai/code/session_014PWWd15hN2tDYWAGEkLWwr