Last active
November 11, 2023 23:48
-
-
Save jmscarnatto/f1d796037d31ec83d2b33f7b13e9d8d3 to your computer and use it in GitHub Desktop.
api_properties_client
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
# frozen_string_literal: true | |
require 'uri' | |
require 'net/http' | |
require 'json' | |
require 'webmock/rspec' | |
class Properties | |
API_URL = 'https://api.stagingeb.com/v1/properties' | |
API_KEY = 'l7u502p8v46ba3ppgvj5y2aad50lb9' | |
def initialize | |
@url = URI(API_URL) | |
@http = Net::HTTP.new(@url.host, @url.port) | |
@http.use_ssl = true | |
end | |
def fetch_properties | |
request = Net::HTTP::Get.new(@url) | |
request['accept'] = 'application/json' | |
request['X-Authorization'] = API_KEY | |
response = @http.request(request) | |
raise 'Error calling the api' unless response.code == '200' | |
data = JSON.parse(response.read_body) | |
data['content'].each do |property| | |
puts property['title'] | |
end | |
end | |
end | |
## How to use th class Properties | |
# Properties.new.fetch_properties | |
## Fisrt install rspec and webmock libraries | |
# gem install rspec webmock | |
RSpec.describe Properties do | |
describe '#fetch_properties' do | |
let(:api_url) { 'https://api.stagingeb.com/v1/properties' } | |
let(:authorization_token) { 'l7u502p8v46ba3ppgvj5y2aad50lb9' } | |
let(:response_body) { '{"content": [{"prop": "number_1", "title": "Property 1"}, {"prop": "number_2", "title": "Property 2"}]}' } | |
it 'fetches properties successfully' do | |
stub_request(:get, api_url) | |
.with( | |
headers: { | |
'Accept' => 'application/json', | |
'X-Authorization' => authorization_token | |
} | |
) | |
.to_return(status: 200, body: response_body, headers: {}) | |
properties_client = Properties.new | |
expect { properties_client.fetch_properties }.to output("Property 1\nProperty 2\n").to_stdout | |
end | |
it 'fails to return values' do | |
stub_request(:get, api_url) | |
.with( | |
headers: { | |
'Accept' => 'application/json', | |
'X-Authorization' => authorization_token | |
} | |
) | |
.to_return(status: 400, body: '', headers: {}) | |
properties_client = Properties.new | |
expect { properties_client.fetch_properties }.to raise_error(RuntimeError) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment