In rspec, we need to make http call for our test to pass. In this case, we are actually making http request which is not a best practice while we are executing tests.

The best way is to fake http request with the actual expected response without making actually going to that url.

For faking http request in ruby, we have couple of gems namely FakeWeb and WebMock.

FakeWeb:

Usage:

  1. Include 'fakeweb' in your Gemfile under test group only.

  2. require it in spec helper.

  3. use it in specs

Syntax:

FakeWeb.register_uri(method, url, :body => "response text, html, xml, json, etc ")

method: you can mention method as :post, :get, etc. Not sure of method, mention ':any'.

url: actual http url you want to fake or stub. You can also add regex.

Advantages:

  1. Fastest way to stub http requests.

  2. Supports all type of NET::HTTP libraries.

  3. Write less stub codes.

Disadvantage:

  1. Doesnt support HTTPClient requests.

For info and usage examples, visit: https://github.com/chrisk/fakeweb

WebMock:

Usage:

  1. Add 'webmock' in your gemfile under test group only. (Do not include it in development mode. You will not be able to make http requests in dev mode.)

  2. require 'webmock/rspec' in spec helper.

  3. use its method to stub requests in specs.

Syntax:

stub_request(method, url).to_return(:body => "response text, html, xml, json, etc ")

Advantages:

  1. Supports all type of HTTP libraries including HTTPClient which FakeWeb doesnt support.

Disadvantage:

  1. Need to write more stub code than FakeWeb.

  2. Stubs all the http requests. We need to add separate code to disable WebMock for specs that does require http requests.

For more info and usage examples, visit: https://github.com/bblimke/webmock

FakeWeb or WebMock

FakeWeb is much more simpler and easier to stub http requests than WebMock. I would recommend FakeWeb. But if you want to stub HTTPClient requests, you have to use WebMock. :-)