Testing an external API using RSpec's request specs

rspec, rspec-rails, ruby, ruby-on-rails

Solution

Yes, it's possible

Basically

require 'net/http'
Net::HTTP.get(URI.parse('http://www.google.com'))
# => Google homepage html

But you may need to mock the response as tests are better not to depend on external resource.

Then you can use mock gems like Fakeweb or similar: https://github.com/chrisk/fakeweb

require 'net/http'
require 'fakeweb'
FakeWeb.register_uri(:get, "http://www.google.com", :body => "Hello World!")

describe "external site" do
  it "returns 'World' by visiting Google" do
    result = Net::HTTP.get(URI.parse('http://www.google.com'))
    result.should match("World")
    #=> true
  end
end

It doesn't matter you get a normal html response or jsonp response. All similar.

The above is low level way. The better way is to use your code in app to check it. But you'll always need mock finally.

Problem

I am trying to use RSpec's request specs to change the host to point to a remote URL instead of localhost:3000. Please let me know if this is possible. Note: Just wanted to mention that the remote URL is just a JSON API.

Original source

Related problems