Initial commit
This commit is contained in:
62
spec/support/api_response_helper.rb
Normal file
62
spec/support/api_response_helper.rb
Normal file
@@ -0,0 +1,62 @@
|
||||
module ApiResponseHelper
|
||||
class ApiResponseServiceException < Exception; end
|
||||
|
||||
class ApiResponseService
|
||||
RESPONSES_FILE_PATH = Rails.root.join("spec/fixtures/responses/responses.json")
|
||||
@@responses_hash = nil
|
||||
|
||||
def self.response_body(object, key)
|
||||
response_part(object, key, :body).to_json
|
||||
end
|
||||
|
||||
def self.response_headers(object, key)
|
||||
response_part(object, key, :headers)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def self.responses
|
||||
unless @@responses_hash.present?
|
||||
fd = File.open(RESPONSES_FILE_PATH, 'r')
|
||||
@@responses_hash = HashWithIndifferentAccess.new(JSON.parse(fd.read))
|
||||
end
|
||||
@@responses_hash
|
||||
end
|
||||
|
||||
def self.object_to_key(object)
|
||||
class_name = case object.class.to_s
|
||||
when "String"
|
||||
object
|
||||
when "Class"
|
||||
object.name
|
||||
else
|
||||
object.class.name
|
||||
end
|
||||
class_name
|
||||
end
|
||||
|
||||
def self.response_part(object, key, part = :body)
|
||||
object_key = object_to_key(object)
|
||||
raise ApiResponseServiceException.new("No #{object_key} in fixtures") unless responses.has_key?(object_key)
|
||||
raise ApiResponseServiceException.new("No #{object_key}/#{key} in fixtures") unless responses[object_key].has_key?(key)
|
||||
responses[object_key][key.to_s][part]
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def api_response_fixture_body(object, key)
|
||||
ApiResponseService.response_body(object.to_s, key)
|
||||
end
|
||||
|
||||
def api_response_fixture_headers(object, key)
|
||||
ApiResponseService.response_headers(object.to_s, key)
|
||||
end
|
||||
|
||||
def api_response_fixture(object, key)
|
||||
{body: api_response_fixture_body(object, key), headers: api_response_fixture_headers(object, key)}
|
||||
end
|
||||
end
|
||||
|
||||
RSpec.configure do |config|
|
||||
config.include ApiResponseHelper
|
||||
end
|
||||
Reference in New Issue
Block a user