Created
April 1, 2025 09:31
-
-
Save nicolas-brousse/95f965d93a2f51089981e23a4fc1401f to your computer and use it in GitHub Desktop.
How to test Rails .rate_limit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "bundler/inline" | |
gemfile(true) do | |
source "https://rubygems.org" | |
gem "rails" | |
# If you want to test against edge Rails replace the previous line with this: | |
# gem "rails", github: "rails/rails", branch: "main" | |
end | |
require "action_controller/railtie" | |
require "minitest/autorun" | |
require "rack/test" | |
class TestApp < Rails::Application | |
config.load_defaults Rails::VERSION::STRING.to_f | |
config.root = __dir__ | |
config.eager_load = false | |
config.hosts << "example.org" | |
config.secret_key_base = "secret_key_base" | |
config.logger = Logger.new($stdout) | |
config.cache_store = :null_store | |
end | |
Rails.application.initialize! | |
Rails.application.routes.draw do | |
get "/", to: "test#index" | |
end | |
class TestController < ActionController::Base | |
include Rails.application.routes.url_helpers | |
def rate_limiting(to:, within:, by:, with:, store:, name:) | |
puts store.inspect | |
super | |
end | |
rate_limit to: 2, within: 2.seconds, only: :index | |
def index | |
head :ok | |
end | |
end | |
class BugTest < ActiveSupport::TestCase | |
include Rack::Test::Methods | |
test "exceeding basic limit" do | |
TestController.cache_store = :memory_store | |
get "/" | |
get "/" | |
assert last_response.ok? | |
get "/" | |
assert_equal last_response.status, 429 | |
end | |
private | |
def app | |
Rails.application | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment