title: How to test HTTParty API call with Ruby and RSpec
body: <p>I am using the HTTParty gem to make a call to the GitHub API to access a list of user's repos.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>I have a mock .json file but not sure how to use it in my test.</p>
  
  <p>Any ideas?</p>
  
  <p><strong>github_api.rb</strong></p>
  
  <pre><code>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
  </code></pre>
  
  <p><strong>github_api_spec.rb</strong></p>
  
  <pre><code>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
  </code></pre>
  
  <p><em>Rest of the files for clarity:</em></p>
  
  <p><strong>results.rb</strong></p>
  
  <pre><code>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 &lt;&lt; repo["language"]
     end
   end
  
   def favourite_language
     get_languages
     @languages.group_by(&amp;:itself).values.max_by(&amp;:size).first
   end
  end
  </code></pre>
  
  <p><strong>application_controller.rb</strong></p>
  
  <pre><code>require './config/environment'
  require 'sinatra/base'
  require './app/models/github_api'
  
  class ApplicationController &lt; 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
  </code></pre>