Class: BeJsonApiResponseFor

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi_rspec/be_json_api_response_for.rb

Overview

Class BeJsonApiResponseFor provides custom RSpec matching for json:api responses for a given object instance. It checks attributes and elements iteratively and fails on the first mismatch that it finds.

It expects a Rack::Response (or similar) object to be passed as the left-side of the comparison and a regular Object-derived instance as the right-side.

Usage:

expect(response).to BeJsonApiResponseFor.new(object_instance)

Author:

Instance Method Summary collapse

Constructor Details

#initialize(object_instance, plural_form = nil) ⇒ BeJsonApiResponseFor

Returns a new instance of BeJsonApiResponseFor.



19
20
21
22
# File 'lib/jsonapi_rspec/be_json_api_response_for.rb', line 19

def initialize(object_instance, plural_form = nil)
  @object_instance = object_instance
  @plural_form = plural_form
end

Instance Method Details

#failure_messageObject



53
54
55
56
# File 'lib/jsonapi_rspec/be_json_api_response_for.rb', line 53

def failure_message
  @failure_message ||= "Expected object [#{@object_instance}] to match"
  "#{@failure_message} - parsed response: #{pretty_response}"
end

#failure_message_when_negatedObject



58
59
60
61
# File 'lib/jsonapi_rspec/be_json_api_response_for.rb', line 58

def failure_message_when_negated
  @failure_message = "handle method 'failure_message_when_negated' in custom_matchers.rb"
  "#{@failure_message}: #{pretty_response}"
end

#matches?(response) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/jsonapi_rspec/be_json_api_response_for.rb', line 24

def matches?(response)
  return false unless valid_response?(response)

  @parsed_response = JSON.parse(response.body)

  return false if response_is_error?
  return false unless valid_data_section?
  if JsonapiRspec.configuration.meta_required
    return false unless valid_meta_section?
  end

  @parsed_response.each do |key, value|
    case key.to_sym
    when :data
      return false unless match_object?(value)
    when :meta
      return false unless valid_meta_section?
    when :jsonapi
      next # this can legally be anything
    when :included
      next # TODO: handle included objects
    else
      return set_failure_message("Unexpected key in response: '#{key}'")
    end
  end

  true
end