Testing Rack::Attack
I'm setting up Rack::Attack for rate limiting. The README is good, but light on testing. Here's how I got it working.
require "test_helper"
class RackAttackTest < ActionDispatch::IntegrationTest
setup do
Rack::Attack.enabled = true
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.cache.store.clear
end
teardown do
Rack::Attack.enabled = false
Rack::Attack.cache.store.clear
end
class AnonTest < RackAttackTest
test "throttle excessive requests by IP address" do
limit = 300
period = 5.minutes
ip = "1.2.3.4"
key = "req/ip:#{ip}"
limit.times do
Rack::Attack.cache.count(key, period)
end
get "/", headers: {REMOTE_ADDR: ip}
assert_response :too_many_requests
Timecop.travel(6.minutes.from_now)
get "/", headers: {REMOTE_ADDR: ip}
assert_response :success
rescue
Timecop.return
end
end
end