3

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.

1

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Hey Billy, instead of this is there a way to set the default host to "www.google.com" so all my requests specs like /users run against that host?
@MadhanPadmanabhan, this should be what you want. You can set google.com as a variable and set query strings separately. Check here: ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/…
Umm, I am getting uninitialized constant Net::Http even when I require it :/
Thanks! Can I set the URI as a variable in a config file so whenever I do a get /users.json the URL gets prepended?
You can set it in spec_helper.rb which is the file you'll always require in tests.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.