PAYATHON 2026

如何在 Rails 8 中用 RSpec 测试 rate_limit

数据小陈

建议用 type: :request 写 RSpec 请求测试,这是验证限流最可靠的方式。先确认测试环境的 Rails.cache 确实能保存数据;清空缓存后,连续请求 create 路由 11 次。前 10 次不应返回 429,第 11 次应返回 429 Too Many Requests。要验证 3 分钟窗口,用 travel 或 travel_to 推进时间,不要用 sleep 真等。

为什么测试里限流可能不生效

Rails 8 的 rate_limit 通过控制器的 before_action 执行,计数保存在 Rails.cache 里。Rails 生成的测试环境经常是这种配置:

# config/environments/test.rb
config.cache_store = :null_store

:null_store 不会保存计数,所以连续请求也不会触发限流。测试时要换成 :memory_store,或者在 spec 里临时替换 Rails.cache。

配置测试缓存

可以在测试环境里这样改:

# config/environments/test.rb
Rails.application.configure do
  config.cache_store = :memory_store
end

如果不想动全局配置,也可以在 spec 里用 around 临时替换:

around do |example|
  old_cache = Rails.cache
  Rails.cache = ActiveSupport::Cache::MemoryStore.new
  example.run
ensure
  Rails.cache = old_cache
end

RSpec 请求测试示例

下面的请求测试验证两件事:3 分钟内第 11 次 POST 到 create 路由会返回 429;窗口过期后请求恢复正常。记得把 /session 换成你实际的登录或 create 路由。

# spec/requests/sessions_rate_limit_spec.rb
require "rails_helper"

RSpec.describe "Sessions rate limit", type: :request do
  include ActiveSupport::Testing::TimeHelpers

  before do
    Rails.cache.clear
  end

  it "允许 3 分钟内前 10 次 create,第 11 次返回 429" do
    10.times do
      post "/session", params: { email: "test@example.com", password: "password" }
      expect(response).not_to have_http_status(:too_many_requests)
    end

    post "/session", params: { email: "test@example.com", password: "password" }

    expect(response).to have_http_status(:too_many_requests)
  end

  it "3 分钟窗口过后恢复请求" do
    10.times do
      post "/session", params: { email: "test@example.com", password: "password" }
    end

    travel 3.minutes + 1.second do
      post "/session", params: { email: "test@example.com", password: "password" }
      expect(response).not_to have_http_status(:too_many_requests)
    end
  end
end

示例里的参数只是占位。如果 SessionsController#create 需要真实用户,换成能走到这个 action 的合法或非法参数都行;测试关注的是第 11 次请求的状态码。

如果自定义了超限响应

原代码没有写 with,默认超限响应通常是 429。如果控制器改成这样:

class SessionsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create,
    with: -> { redirect_to new_session_path, alert: "请求过于频繁,请稍后再试" }
end

那 spec 就不能断言 429,而要断言重定向和 flash:

expect(response).to redirect_to(new_session_path)
expect(flash[:alert]).to eq("请求过于频繁,请稍后再试")

注意事项

  • 每个用例前清缓存,避免上一个用例的计数影响结果。
  • 不要用 sleep 3.minutes 测窗口,太慢;用 travel 或 travel_to。
  • Rails 8 的 rate_limit 默认按 request.remote_ip 计数;如果你用了 by:,要保证测试请求落在同一个计数 key 上。
  • 并行测试如果共享缓存,可能互相影响。建议给测试单独缓存,或清理缓存,必要时给 rate_limit 指定独立的 store 或 name。
  • 如果应用使用 Redis 等外部缓存,要确认 Rails.cache.clear 的影响范围,避免清掉其他测试数据。

备注:内容仅供参考。