Skip to content

Instantly share code, notes, and snippets.

@Astr0surf3r
Created July 3, 2024 02:02
Show Gist options
  • Save Astr0surf3r/e11c97dcd312843c9eb6aebab84dc3ae to your computer and use it in GitHub Desktop.
Save Astr0surf3r/e11c97dcd312843c9eb6aebab84dc3ae to your computer and use it in GitHub Desktop.
easybroker API - creo una clase y un archivo de prueba en ruby para test de la clase
require 'uri'
require 'net/http'
require 'json'
class EasyBrokerClient
BASE_URL = 'https://api.easybroker.com/v1/properties'
def initialize(api_key)
@api_key = api_key
end
def list_properties
url = URI(BASE_URL)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request['accept'] = 'application/json'
request['X-Authorization'] = @api_key
response = http.request(request)
case response
when Net::HTTPSuccess
JSON.parse(response.body)['content'].map { |property| property['title'] }
when Net::HTTPUnauthorized
raise "Unauthorized: Check your API key."
end
end
end
#client = EasyBrokerClient.new('API_KEY')
#puts client.list_properties
source 'https://rubygems.org'
gem 'uri'
gem 'json'
gem 'rspec'
gem 'webmock'
require 'rspec'
require 'webmock/rspec'
require_relative '../easy_broker_client'
RSpec.describe EasyBrokerClient do
before(:all) do
@api_key = 'API_KEY'
@client = EasyBrokerClient.new(@api_key)
end
describe '#list_properties' do
context 'when the API key is valid' do
it 'returns an array of property titles' do
stub_request(:get, "https://api.easybroker.com/v1/properties")
.with(headers: {
'accept' => 'application/json',
'X-Authorization' => @api_key
})
.to_return(
status: 200,
body: {
content: [
{ title: 'Property 1' },
{ title: 'Property 2' },
{ title: 'Property 3' }
]
}.to_json,
headers: { 'Content-Type' => 'application/json' }
)
titles = @client.list_properties
expect(titles).to be_an_instance_of(Array)
expect(titles).to all(be_an_instance_of(String))
expect(titles).to eq(['Property 1', 'Property 2', 'Property 3'])
end
end
context 'when the API key is invalid' do
it 'raises an unauthorized error' do
stub_request(:get, "https://api.easybroker.com/v1/properties")
.with(headers: {
'accept' => 'application/json',
'X-Authorization' => @api_key
})
.to_return(status: 401)
expect { @client.list_properties }.to raise_error(RuntimeError, "Unauthorized: Check your API key.")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment