Skip to content

Commit 2ef4f0a

Browse files
authored
Merge pull request #13 from happycollision/fix-issue-5
Fix issue 5
2 parents ae8dc12 + 046fa65 commit 2ef4f0a

File tree

4 files changed

+26
-1
lines changed

4 files changed

+26
-1
lines changed

lib/jsonapi_spec_helpers.rb

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
require 'jsonapi_spec_helpers/helpers'
44
require 'jsonapi_spec_helpers/payload'
55
require 'jsonapi_spec_helpers/payload_sanitizer'
6+
require 'jsonapi_spec_helpers/errors'
67

78
module JsonapiSpecHelpers
89
def self.included(klass)

lib/jsonapi_spec_helpers/errors.rb

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
module JsonapiSpecHelpers
2+
module Errors
3+
class Base < StandardError; end
4+
class IncludedOutOfBounds < Base
5+
def initialize(type, index, array)
6+
@type = type; @index = index; @array = array
7+
end
8+
9+
def message
10+
"You attempted to get an item at index #{@index} of the type '#{@type}' " \
11+
"from the included property of your JSON payload. But it contained " \
12+
"#{@array.length} '#{@type}'"
13+
end
14+
end
15+
end
16+
end

lib/jsonapi_spec_helpers/helpers.rb

+5-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@ def json_includes(type, *indices)
3939
indices = (0...included.length).to_a if indices.empty?
4040
includes = []
4141
indices.each do |index|
42-
includes << json_item(from: included.at(index))
42+
single_included = included.at(index)
43+
if single_included.nil?
44+
raise Errors::IncludedOutOfBounds.new(type, index, included)
45+
end
46+
includes << json_item(from: single_included)
4347
end
4448
includes
4549
end

spec/helpers_spec.rb

+4
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,10 @@
173173
it 'is only includes of a given type at indices' do
174174
expect(json_includes('comments', 1).length).to eq(1)
175175
end
176+
177+
it 'throws when asking for an index beyond the length of the includes' do
178+
expect{ json_includes('comments', 99) }.to raise_error JsonapiSpecHelpers::Errors::IncludedOutOfBounds
179+
end
176180
end
177181
end
178182

0 commit comments

Comments
 (0)