1
0
Fork 0
mirror of https://github.com/nov/fb_graph2 synced 2023-03-27 23:22:15 -04:00
fb_graph2/spec/spec_helper/mock_graph.rb

97 lines
2.3 KiB
Ruby
Raw Normal View History

2014-05-21 01:03:21 -04:00
require 'webmock/rspec'
module MockGraph
def mock_graph(method, path, response_path, options = {})
stub_request(
method,
2014-06-10 11:53:58 -04:00
endpoint_for(path, options)
2014-05-21 01:03:21 -04:00
).with(
request_for(method, options)
).to_return(
response_for(response_path, options)
)
if block_given?
response = yield
a_request(
method,
2014-09-01 00:23:54 -04:00
endpoint_for(path, options)
2014-05-21 01:03:21 -04:00
).with(
request_for(method, options)
).should have_been_made.once
response
end
end
2014-05-27 22:41:04 -04:00
def mock_json(response_path)
2014-06-11 04:45:05 -04:00
content = response_for(response_path)[:body].read
MultiJson.load(content).with_indifferent_access
rescue MultiJson::DecodeError
content
2014-05-27 22:41:04 -04:00
end
2014-06-10 11:53:58 -04:00
def request_to(path, method = :get, options = {})
2014-05-21 01:03:21 -04:00
raise_error { |e|
e.should be_instance_of WebMock::NetConnectNotAllowedError
e.message.should include("Unregistered request: #{method.to_s.upcase}")
2014-06-10 11:53:58 -04:00
e.message.should include(endpoint_for path, options)
2014-05-21 01:03:21 -04:00
}
end
private
2014-06-10 11:53:58 -04:00
def endpoint_for(path, options = {})
2014-09-01 00:23:54 -04:00
api_version = unless options[:disable_api_versioning]
2014-06-10 11:53:58 -04:00
options[:api_version] || FbGraph2.api_version
end
File.join FbGraph2.root_url, api_version.to_s, path
2014-05-21 01:03:21 -04:00
end
def request_for(method, options = {})
request = {}
if options[:access_token]
2014-05-21 05:20:41 -04:00
request[:headers] ||= {}
request[:headers] = {
authorization: "Bearer #{options[:access_token]}"
}
2014-05-21 01:03:21 -04:00
end
if options[:params]
case method
2014-06-03 05:26:33 -04:00
when :post, :put, :delete
2014-05-21 01:03:21 -04:00
request[:body] = options[:params]
else
request[:query] = options[:params]
end
end
request
end
def response_for(response_path, options = {})
response = {}
response[:body] = response_file_for response_path
if options[:status]
response[:status] = options[:status]
end
response
end
def response_file_for(response_path)
_response_file_path_ = if File.exist? response_path
response_path
else
File.join(
File.dirname(__FILE__), '../mock_json', "#{response_path}.json"
)
end
unless File.exist? _response_file_path_
response_file_required! _response_file_path_
end
File.new _response_file_path_, 'r', encoding: 'utf-8'
end
def response_file_required!(response_path)
warn 'No response file found.'
end
end
include MockGraph
WebMock.disable_net_connect!