cacheable_response.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # frozen_string_literal: true
  2. RSpec::Matchers.define :have_cacheable_headers do
  3. match do |response|
  4. @response = response
  5. @errors = [].tap do |errors|
  6. errors << check_cookies
  7. errors << check_cookie_headers
  8. errors << check_session
  9. errors << check_cache_control
  10. errors << check_vary if @expected_vary.present?
  11. end
  12. @errors.compact.empty?
  13. end
  14. chain :with_vary do |string|
  15. @expected_vary = string
  16. end
  17. failure_message do
  18. <<~ERROR
  19. Expected that the response would be cacheable but it was not:
  20. - #{@errors.compact.join("\n - ")}
  21. ERROR
  22. end
  23. def check_vary
  24. "Response `Vary` header does not contain `#{@expected_vary}`" unless @response.headers['Vary'].include?(@expected_vary)
  25. end
  26. def check_cookies
  27. 'Reponse cookies are present' unless @response.cookies.empty?
  28. end
  29. def check_cookie_headers
  30. 'Response `Set-Cookies` headers are present' if @response.headers['Set-Cookies'].present?
  31. end
  32. def check_session
  33. 'The session is not empty' unless session.empty?
  34. end
  35. def check_cache_control
  36. 'The `Cache-Control` header does not contain `public`' unless @response.headers['Cache-Control'].include?('public')
  37. end
  38. end