Created
May 6, 2014 15:33
-
-
Save deitrick/ca750df19252181450ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source "https://rubygems.org" | |
gem 'faraday' | |
gem 'rspec' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'faraday' | |
require 'json' | |
class HttpResponse | |
def initialize(url) | |
@url = url | |
end | |
def headers | |
response.headers | |
end | |
def body | |
response.body | |
end | |
def status_code | |
response.status | |
end | |
def is_json? | |
response.headers["content-type"].include?('application/json') | |
end | |
def response_json | |
if is_json? | |
JSON.parse(response.body) | |
end | |
end | |
private | |
def response | |
Faraday.get(@url) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
require 'faraday' | |
require_relative 'response' | |
describe HttpResponse do | |
before { | |
@response = HttpResponse.new('http://google.com') | |
} | |
it 'should return the headers as a hash with strings as keys' do | |
headers = @response.headers | |
expect(headers.has_key?('location')).to eq true | |
end | |
it 'should return the body' do | |
body = @response.body | |
expect(body).to eq "<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n<TITLE>301 Moved</TITLE></HEAD><BODY>\n<H1>301 Moved</H1>\nThe document has moved\n<A HREF=\"http://www.google.com/\">here</A>.\r\n</BODY></HTML>\r\n" | |
end | |
it 'should return a status code' do | |
code = @response.status_code | |
expect(code).to eq 301 | |
end | |
it 'should return a true if the content-type is json' do | |
@response = HttpResponse.new('http://www.reddit.com/r/aww/.json') | |
result = @response.is_json? | |
expect(result).to eq true | |
end | |
it 'should return the nil if the content-type is not' do | |
hash = @response.response_json | |
expect(hash).to eq nil | |
end | |
it 'should return a hash if content-type is json' do | |
@response = HttpResponse.new('http://www.reddit.com/r/aww/.json') | |
expect(@response.response_json).to be_kind_of Hash | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment