Skip to content

Commit

Permalink
Freeze time to fix flakey specs
Browse files Browse the repository at this point in the history
  • Loading branch information
jdelStrother committed Nov 20, 2023
1 parent 27ada96 commit b4328d8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
11 changes: 8 additions & 3 deletions spec/rack_attack_throttle_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -146,6 +150,7 @@
end

describe 'Rack::Attack.throttle with throttle_discriminator_normalizer' do
freeze_time!
before do
@period = 60
@emails = [
Expand Down
6 changes: 6 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
require "rack/test"
require "active_support"
require "rack/attack"
require "timecop"

if RUBY_ENGINE == "ruby"
require "byebug"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit b4328d8

Please sign in to comment.