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.
Include 'fakeweb' in your Gemfile under test group only.
require it in spec helper.
use it in specs
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.
Fastest way to stub http requests.
Supports all type of NET::HTTP libraries.
Write less stub codes.
- Doesnt support HTTPClient requests.
For info and usage examples, visit: https://github.com/chrisk/fakeweb
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.)
require 'webmock/rspec' in spec helper.
use its method to stub requests in specs.
stub_request(method, url).to_return(:body => "response text, html, xml, json, etc ")
- Supports all type of HTTP libraries including HTTPClient which FakeWeb doesnt support.
Need to write more stub code than FakeWeb.
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. :-)
Subscribe to Engineering At Kiprosh
Get the latest posts delivered right to your inbox