From a0824406c3a02dfd92368fcbc0c9a96924d7471c Mon Sep 17 00:00:00 2001 From: Jonathan del Strother Date: Mon, 20 Nov 2023 15:39:53 +0000 Subject: [PATCH] Freeze time to fix flakey specs --- spec/rack_attack_throttle_spec.rb | 11 ++++++++--- spec/spec_helper.rb | 6 ++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/spec/rack_attack_throttle_spec.rb b/spec/rack_attack_throttle_spec.rb index 0b0d68ac..e73c85f9 100644 --- a/spec/rack_attack_throttle_spec.rb +++ b/spec/rack_attack_throttle_spec.rb @@ -3,8 +3,9 @@ require_relative 'spec_helper' describe 'Rack::Attack.throttle' do + freeze_time! before do - @period = 60 # Use a long period; failures due to cache key rotation less likely + @period = 60 Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new Rack::Attack.throttle('ip/sec', limit: 1, period: @period) { |req| req.ip } end @@ -61,8 +62,9 @@ end describe 'Rack::Attack.throttle with limit as proc' do + freeze_time! before do - @period = 60 # Use a long period; failures due to cache key rotation less likely + @period = 60 Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new Rack::Attack.throttle('ip/sec', limit: lambda { |_req| 1 }, period: @period) { |req| req.ip } end @@ -92,8 +94,9 @@ end describe 'Rack::Attack.throttle with period as proc' do + freeze_time! before do - @period = 60 # Use a long period; failures due to cache key rotation less likely + @period = 60 Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new Rack::Attack.throttle('ip/sec', limit: lambda { |_req| 1 }, period: lambda { |_req| @period }) { |req| req.ip } end @@ -123,6 +126,7 @@ end describe 'Rack::Attack.throttle with block retuning nil' do + freeze_time! before do @period = 60 Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new @@ -146,6 +150,7 @@ end describe 'Rack::Attack.throttle with throttle_discriminator_normalizer' do + freeze_time! before do @period = 60 @emails = [ diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f529e6a1..76e2ed3b 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -7,6 +7,7 @@ require "rack/test" require "active_support" require "rack/attack" +require "timecop" if RUBY_ENGINE == "ruby" require "byebug" @@ -58,6 +59,11 @@ def self.it_allows_ok_requests _(last_response.body).must_equal 'Hello World' end end + + def self.freeze_time! + before { Timecop.freeze } + after { Timecop.return } + end end class Minitest::SharedExamples < Module