Gregor Gregor - 1 month ago 11
Ruby Question

How should I test this code with rspec rails?

In my rails application I have a module with an API call that I would like to write rspec tests for. What would you write as proper tests for this? I have read not to combine httparty with rspec because it is very slow and now I have no idea how to do this. Thanks for the advice!

module BandsInTown
class API
attr_reader :artist_name, :info, :events

def initialize(artist_name)
@artist_name = artist_name
end

def artist_info
@info = fetch_data
end

def artist_events
@events = fetch_data 'events'
end

private

def fetch_data(endpoint = nil)
request_url = "http://api.bandsintown.com/artists/#{[@artist_name, endpoint].compact.join('/')}.json?api_version=2.0&app_id=AUTH_KEY"
resp = HTTParty.get(request_url)
return false if resp.code != 200
resp
end
end
end

Answer

I would use webmock to get around making API requests.

Here's an example on how the code in yout spec_helper.rb could look like:

require 'webmock/rspec'

def stub_api_requests
  response = File.read('spec/fixtures/payload.json')
  stub_request(:get, %r{http:\/\/api.bandsintown.com\/artists/\/(.)*})
    .to_return(
      status: 200,
      body: response
    )
end

config.before(:each) do
  stub_api_requests
end
Comments