|
| 1 | +require "json" |
| 2 | + |
| 3 | +module GovukConditionalContentItemLoaderTestHelpers |
| 4 | + Response = Struct.new(:status, :body, :headers) do |
| 5 | + def to_h |
| 6 | + JSON.parse(body) |
| 7 | + end |
| 8 | + end |
| 9 | + |
| 10 | + # Stubs the loader returns a content item |
| 11 | + # The following options can be passed in: |
| 12 | + # |
| 13 | + # :max_age will set the max-age of the Cache-Control header in the response. Defaults to 900 |
| 14 | + # :private if true, the Cache-Control header will include the "private" directive. By default it |
| 15 | + # will include "public" |
| 16 | + def stub_conditional_loader_returns_content_item(body, options = {}) |
| 17 | + body.to_json unless body.is_a?(String) |
| 18 | + max_age = options.fetch(:max_age, 900) |
| 19 | + visibility = options[:private] ? "private" : "public" |
| 20 | + |
| 21 | + response = Response.new(200, body, { |
| 22 | + cache_control: "#{visibility}, max-age=#{max_age}", |
| 23 | + date: Time.now.httpdate, |
| 24 | + }) |
| 25 | + |
| 26 | + loader = instance_double(GovukConditionalContentItemLoader, load: response) |
| 27 | + |
| 28 | + allow(GovukConditionalContentItemLoader).to receive(:new).with(request: anything) |
| 29 | + .and_return(loader) |
| 30 | + allow(loader).to receive(:load).and_return(body) |
| 31 | + |
| 32 | + response |
| 33 | + end |
| 34 | + |
| 35 | + # Stubs the loader returns a error response |
| 36 | + # The following options can be passed in: |
| 37 | + # |
| 38 | + # :status the HTTP status code for the error. Defaults to 404 |
| 39 | + # :message the error message. Defaults to "Not Found" |
| 40 | + # :error_details optional additional error details to attach to the exception |
| 41 | + # :http_body optional raw response body to attach to the exception |
| 42 | + def stub_conditional_loader_does_not_return_content_item(options = {}) |
| 43 | + status = options.fetch(:status, 404) |
| 44 | + message = options.fetch(:message, "Not Found") |
| 45 | + error_details = options[:error_details] |
| 46 | + http_body = options[:http_body] |
| 47 | + |
| 48 | + error = GdsApi::HTTPErrorResponse.new(status, message, error_details, http_body) |
| 49 | + |
| 50 | + loader = instance_double(GovukConditionalContentItemLoader) |
| 51 | + |
| 52 | + allow(GovukConditionalContentItemLoader).to receive(:new).with(request: anything) |
| 53 | + .and_return(loader) |
| 54 | + allow(loader).to receive(:load).and_raise(error) |
| 55 | + |
| 56 | + error |
| 57 | + end |
| 58 | +end |
0 commit comments