class Rack::Spec::ResponseValidation::Validator

Public Class Methods

new(env: nil, response: nil, schema: nil) click to toggle source

@param env [Hash] Rack env @param response [Array] Rack response @param schema [JsonSchema::Schema] Schema object

# File lib/rack/spec/response_validation.rb, line 25
def initialize(env: nil, response: nil, schema: nil)
  @env = env
  @response = response
  @schema = schema
end

Public Instance Methods

body() click to toggle source

@return [String] Response body

# File lib/rack/spec/response_validation.rb, line 80
def body
  result = ""
  @response[2].each {|str| result << str }
  result
end
call() click to toggle source

Raises an error if any error detected, skipping validation for non-defined link @raise [Rack::Spec::ResponseValidation::InvalidResponse]

# File lib/rack/spec/response_validation.rb, line 33
def call
  if has_link_for_current_action?
    case
    when !has_json_content_type?
      raise InvalidResponseContentType
    when !valid?
      raise InvalidResponseType, validator.errors
    end
  end
end
data() click to toggle source

@return [Array, Hash] Response body data, decoded from JSON

# File lib/rack/spec/response_validation.rb, line 64
def data
  MultiJson.decode(body)
end
example_item() click to toggle source

@return [Hash] Choose an item from response data, to be validated

# File lib/rack/spec/response_validation.rb, line 55
def example_item
  if has_list_data?
    data.first
  else
    data
  end
end
has_json_content_type?() click to toggle source

@return [true, false] True if response Content-Type is for JSON

# File lib/rack/spec/response_validation.rb, line 45
def has_json_content_type?
  %r<\Aapplication/.*json> === headers["Content-Type"]
end
headers() click to toggle source

@return [Hash] Response headers

# File lib/rack/spec/response_validation.rb, line 75
def headers
  @response[1]
end
valid?() click to toggle source

@return [true, false] True if given data is valid to the JSON schema

# File lib/rack/spec/response_validation.rb, line 50
def valid?
  validator.validate(example_item)
end
validator() click to toggle source

@return [JsonSchema::Validator] @note The result is memoized for returning errors in invalid case

# File lib/rack/spec/response_validation.rb, line 70
def validator
  @validator ||= JsonSchema::Validator.new(schema_for_current_link)
end