diff --git a/lib/jsonapi_spec_helpers.rb b/lib/jsonapi_spec_helpers.rb index 4d928bd..8850f90 100644 --- a/lib/jsonapi_spec_helpers.rb +++ b/lib/jsonapi_spec_helpers.rb @@ -3,6 +3,7 @@ require 'jsonapi_spec_helpers/helpers' require 'jsonapi_spec_helpers/payload' require 'jsonapi_spec_helpers/payload_sanitizer' +require 'jsonapi_spec_helpers/errors' module JsonapiSpecHelpers def self.included(klass) diff --git a/lib/jsonapi_spec_helpers/errors.rb b/lib/jsonapi_spec_helpers/errors.rb new file mode 100644 index 0000000..b426089 --- /dev/null +++ b/lib/jsonapi_spec_helpers/errors.rb @@ -0,0 +1,16 @@ +module JsonapiSpecHelpers + module Errors + class Base < StandardError; end + class IncludedOutOfBounds < Base + def initialize(type, index, array) + @type = type; @index = index; @array = array + end + + def message + "You attempted to get an item at index #{@index} of the type '#{@type}' " \ + "from the included property of your JSON payload. But it contained " \ + "#{@array.length} '#{@type}'" + end + end + end +end \ No newline at end of file diff --git a/lib/jsonapi_spec_helpers/helpers.rb b/lib/jsonapi_spec_helpers/helpers.rb index e37d6c3..d19c74b 100644 --- a/lib/jsonapi_spec_helpers/helpers.rb +++ b/lib/jsonapi_spec_helpers/helpers.rb @@ -39,7 +39,11 @@ def json_includes(type, *indices) indices = (0...included.length).to_a if indices.empty? includes = [] indices.each do |index| - includes << json_item(from: included.at(index)) + single_included = included.at(index) + if single_included.nil? + raise Errors::IncludedOutOfBounds.new(type, index, included) + end + includes << json_item(from: single_included) end includes end diff --git a/spec/helpers_spec.rb b/spec/helpers_spec.rb index ece18e1..eb4fa53 100644 --- a/spec/helpers_spec.rb +++ b/spec/helpers_spec.rb @@ -173,6 +173,10 @@ it 'is only includes of a given type at indices' do expect(json_includes('comments', 1).length).to eq(1) end + + it 'throws when asking for an index beyond the length of the includes' do + expect{ json_includes('comments', 99) }.to raise_error JsonapiSpecHelpers::Errors::IncludedOutOfBounds + end end end