Skip to content

Commit

Permalink
feature: pokeapi integration
Browse files Browse the repository at this point in the history
  • Loading branch information
AdrienGiboire committed Oct 13, 2021
1 parent e7839f1 commit 8866bb2
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
42 changes: 42 additions & 0 deletions lib/pokeapi.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
require 'net/http'

module Pokeapi
BASE_URI = "https://pokeapi.co/api/v2"

class Resource
def self.request resource
uri = URI("#{BASE_URI}/#{resource}")
response = Net::HTTP.get_response(uri)
JSON.parse(response.body)
end

def self.get params = nil
throw "You can't call Resource#get directly" if name.demodulize == 'Resource'

request "#{name.demodulize.downcase}/#{params}"
end

def self.get_all
next_url_params = nil
results = []

loop do
data = get next_url_params
results += data["results"]

next_url_params = if data["next"] then
"?#{data["next"].split("?").try(:last)}"
else
nil
end

break unless next_url_params
end

results
end
end

class Pokemon < Resource
end
end
44 changes: 44 additions & 0 deletions test/lib/pokeapi_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
require "test_helper"
require 'pokeapi'

class PokeapiApiResourceTest < ActiveSupport::TestCase
test "Resource#request" do
VCR.use_cassette("pokeapi_resource_request") do
response = Pokeapi::Resource.request 'pokemon'
assert :success
assert response["count"] > 0
end
end

test "Resource#get(params) throws an error" do
VCR.use_cassette("pokeapi_resource_get") do
assert_raises StandardError do
response = Pokeapi::Resource.get 'pokemon'
end
end
end

test "Resource#get_all throws an error" do
VCR.use_cassette("pokeapi_resource_get_all") do
assert_raises StandardError do
response = Pokeapi::Resource.get_all
end
end
end
end

class PokeapiApiPokemonTest < ActiveSupport::TestCase
test "Pokemon#get_all retrieves a list of pokemons from API" do
VCR.use_cassette("pokeapi_pokemon_get_all") do
response = Pokeapi::Pokemon.get_all
assert :success
end
end

test "Resource#get_all throws an error" do
VCR.use_cassette("pokeapi_resource_get_1") do
response = Pokeapi::Pokemon.get '1'
assert response["id"] == 1
end
end
end
7 changes: 7 additions & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
ENV['RAILS_ENV'] ||= 'test'
require_relative "../config/environment"
require "rails/test_help"
require 'webmock/minitest'
require 'vcr'

class ActiveSupport::TestCase
# Run tests in parallel with specified workers
Expand All @@ -11,3 +13,8 @@ class ActiveSupport::TestCase

# Add more helper methods to be used by all tests here...
end

VCR.configure do |config|
config.cassette_library_dir = "fixtures/vcr_cassettes"
config.hook_into :webmock
end

0 comments on commit 8866bb2

Please sign in to comment.