rate_limit_headers_spec.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. RSpec.describe Api::RateLimitHeaders do
  4. controller(ApplicationController) do
  5. include Api::RateLimitHeaders
  6. def show
  7. head 200
  8. end
  9. end
  10. before do
  11. routes.draw { get 'show' => 'anonymous#show' }
  12. end
  13. describe 'rate limiting' do
  14. context 'when throttling is off' do
  15. before do
  16. request.env['rack.attack.throttle_data'] = nil
  17. end
  18. it 'does not apply rate limiting' do
  19. get 'show'
  20. expect(response.headers['X-RateLimit-Limit']).to be_nil
  21. expect(response.headers['X-RateLimit-Remaining']).to be_nil
  22. expect(response.headers['X-RateLimit-Reset']).to be_nil
  23. end
  24. end
  25. context 'when throttling is on' do
  26. let(:start_time) { DateTime.new(2017, 1, 1, 12, 0, 0).utc }
  27. before do
  28. request.env['rack.attack.throttle_data'] = { 'throttle_authenticated_api' => { limit: 100, count: 20, period: 10 } }
  29. travel_to start_time do
  30. get 'show'
  31. end
  32. end
  33. it 'applies rate limiting limit header' do
  34. expect(response.headers['X-RateLimit-Limit']).to eq '100'
  35. end
  36. it 'applies rate limiting remaining header' do
  37. expect(response.headers['X-RateLimit-Remaining']).to eq '80'
  38. end
  39. it 'applies rate limiting reset header' do
  40. expect(response.headers['X-RateLimit-Reset']).to eq (start_time + 10.seconds).iso8601(6)
  41. end
  42. end
  43. end
  44. end