Add have_cacheable_headers matcher for responses (#31727)

This commit is contained in:
Matt Jankowski 2024-09-03 11:35:19 -04:00 committed by GitHub
parent 490bdb7944
commit e1fa456c7c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 96 additions and 65 deletions

View file

@ -1,14 +0,0 @@
# frozen_string_literal: true
shared_examples 'cacheable response' do |expects_vary: false|
it 'sets correct cache and vary headers and does not set cookies or session', :aggregate_failures do
expect(response.cookies).to be_empty
expect(response.headers['Set-Cookies']).to be_nil
expect(session).to be_empty
expect(response.headers['Vary']).to include(expects_vary) if expects_vary
expect(response.headers['Cache-Control']).to include('public')
end
end

View file

@ -0,0 +1,50 @@
# frozen_string_literal: true
RSpec::Matchers.define :have_cacheable_headers do
match do |response|
@response = response
@errors = [].tap do |errors|
errors << check_cookies
errors << check_cookie_headers
errors << check_session
errors << check_cache_control
errors << check_vary if @expected_vary.present?
end
@errors.compact.empty?
end
chain :with_vary do |string|
@expected_vary = string
end
failure_message do
<<~ERROR
Expected that the response would be cacheable but it was not:
- #{@errors.compact.join("\n - ")}
ERROR
end
def check_vary
puts @expected_vary
pp @response.headers
"Response `Vary` header does not contain `#{@expected_vary}`" unless @response.headers['Vary'].include?(@expected_vary)
end
def check_cookies
'Reponse cookies are present' unless @response.cookies.empty?
end
def check_cookie_headers
'Response `Set-Cookies` headers are present' if @response.headers['Set-Cookies'].present?
end
def check_session
'The session is not empty' unless session.empty?
end
def check_cache_control
'The `Cache-Control` header does not contain `public`' unless @response.headers['Cache-Control'].include?('public')
end
end