Skip to content

Commit 046fa65

Browse files
Better error handling pattern
Sets up a module in the same fashion as the JsonapiCompliable gem
1 parent 2941496 commit 046fa65

File tree

5 files changed

+19
-14
lines changed

5 files changed

+19
-14
lines changed

lib/jsonapi_spec_helpers.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +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/error'
6+
require 'jsonapi_spec_helpers/errors'
77

88
module JsonapiSpecHelpers
99
def self.included(klass)

lib/jsonapi_spec_helpers/error.rb

-2
This file was deleted.

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

+1-10
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,7 @@ def json_includes(type, *indices)
4141
indices.each do |index|
4242
single_included = included.at(index)
4343
if single_included.nil?
44-
raise JsonapiSpecHelpersError,
45-
included_out_of_bounds_error(type, index, included)
44+
raise Errors::IncludedOutOfBounds.new(type, index, included)
4645
end
4746
includes << json_item(from: single_included)
4847
end
@@ -101,12 +100,4 @@ def jsonapi_payload(input)
101100
PayloadSanitizer.new(input).sanitize
102101
end
103102
end
104-
105-
private
106-
107-
def included_out_of_bounds_error(type, index, array)
108-
"You attempted to get an item at index #{index} of the type '#{type}' " \
109-
"from the included property of your JSON payload. But it contained " \
110-
"#{array.length} '#{type}'"
111-
end
112103
end

spec/helpers_spec.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@
175175
end
176176

177177
it 'throws when asking for an index beyond the length of the includes' do
178-
expect{ json_includes('comments', 99) }.to raise_error JsonapiSpecHelpersError
178+
expect{ json_includes('comments', 99) }.to raise_error JsonapiSpecHelpers::Errors::IncludedOutOfBounds
179179
end
180180
end
181181
end

0 commit comments

Comments
 (0)