I am using the HTTParty gem to make a call to the GitHub API to access a list of user's repos.
It is a very simple application using Sinatra that displays a user's favourite programming language based on the most common language that appears in their repos.
I am a bit stuck on how I can write an RSpec expectation that mocks out the actual API call and instead just checks that json data is being returned.
I have a mock .json file but not sure how to use it in my test.
Any ideas?
github_api.rb
require 'httparty'
class GithubApi
attr_reader :username, :data, :languages
def initialize(username)
@username = username
@response = HTTParty.get("https://api.github.com/users/#{@username}/repos")
@data = JSON.parse(@response.body)
end
end
github_api_spec.rb
require './app/models/github_api'
require 'spec_helper'
describe GithubApi do
let(:github_api) { GithubApi.new('mock_user') }
it "receives a json response" do
end
end
Rest of the files for clarity:
results.rb
require 'httparty'
require_relative 'github_api'
class Results
def initialize(github_api = Github.new(username))
@github_api = github_api
@languages = []
end
def get_languages
@github_api.data.each do |repo|
@languages << repo["language"]
end
end
def favourite_language
get_languages
@languages.group_by(&:itself).values.max_by(&:size).first
end
end
application_controller.rb
require './config/environment'
require 'sinatra/base'
require './app/models/github_api'
class ApplicationController < Sinatra::Base
configure do
enable :sessions
set :session_secret, "@3x!ilt£"
set :views, 'app/views'
end
get "/" do
erb :index
end
post "/user" do
@github = GithubApi.new(params[:username])
@results = Results.new(@github)
@language = @results.favourite_language
session[:language] = @language
session[:username] = params[:username]
redirect '/results'
end
get "/results" do
@language = session[:language]
@username = session[:username]
erb :results
end
run! if app_file == $0
end