Class: BeJsonApiResponseFor

Inherits:
Object
  • Object
show all
Includes:
JsonapiRspec
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:

Constant Summary

Constants included from JsonapiRspec

JsonapiRspec::VERSION

Instance Method Summary collapse

Methods included from JsonapiRspec

configure, #failure_message_when_negated, root

Constructor Details

#initialize(object_instance, plural_form = nil) ⇒ BeJsonApiResponseFor

Initialize an instance of the BeJsonApiResponseFor class

Parameters:

  • object_instance (Object)

    Any instantiated object that responds to the attribute-related method calls passed in by the json:api

  • plural_form (String) (defaults to: nil)

    Sometimes the ActiveSupport::Inflector has problems with pluralizing certain strings. This allows setting of the plural form directly. It should be the lowercase, dasherized plural form of the passed object_instance.



32
33
34
35
# File 'lib/jsonapi_rspec/be_json_api_response_for.rb', line 32

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

Instance Method Details

#matches?(response) ⇒ Boolean

Gets called by RSpec or by the camel_cased syntactical method below.

Parameters:

  • response (Rack::Response)

    A type of Rack::Response or any object that responds to the :body method.

Returns:

  • (Boolean)

    true if it matches, false if not



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/jsonapi_rspec/be_json_api_response_for.rb', line 44

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?

  return false if JsonapiRspec.configuration.meta_required && !valid_meta_section?

  @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
    when :links
      next # TODO: handle links objects
    else
      return failure_message(FailureMessages::UNEXPECTED_TOP_LVL_KEY % key)
    end
  end

  true
end