Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created January 13, 2021 22:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timuruski/2eb03fdda7b078e17d313ba8ffb6793d to your computer and use it in GitHub Desktop.
Save timuruski/2eb03fdda7b078e17d313ba8ffb6793d to your computer and use it in GitHub Desktop.
Example of a flexible pattern for making HTTP requests with Ruby Net:HTTP
require "json"
require "net/http"
require "uri"
# The standard library Net::HTTP module is a bit convoluted, but here is an example of a flexible
# system for making different kinds of HTTP requests. To see some convenience methods you can
# consult the docs: https://ruby-doc.org/stdlib-2.5.5/libdoc/net/http/rdoc/Net/HTTP.html
class HttpConnection
def get(url, params = nil)
url = URI.parse(url.to_s)
url.query = URI.encode_www_form(params) if params
request = Net::HTTP::Get.new(url.to_s)
http_request(request)
end
def post(url, params = nil)
request = Net::HTTP::Post.new(url)
request.body = URI.encode_www_form(params) if params
http_request(request)
end
private def http_request(request)
uri = URI.parse(request.path)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http|
http.request(request)
}
end
end
require "webmock/rspec"
RSpec.describe HttpConnection do
describe "#get" do
it "can make a GET request" do
get_request = stub_request(:get, "httpbin.org/get").with(query: {"msg" => "Hello, world!"})
subject.get("http://httpbin.org/get", msg: "Hello, world!")
expect(get_request).to have_been_requested
end
it "returns a response object" do
stub_request(:get, "httpbin.org/get").to_return(body: "Well, hello there!")
response = subject.get("http://httpbin.org/get")
expect(response.code).to eq "200"
expect(response.body).to eq "Well, hello there!"
end
end
describe "#post" do
it "can make a POST request" do
post_request = stub_request(:post, "httpbin.org/post").with(body: "msg=Hello%2C+world%21")
subject.post("http://httpbin.org/post", msg: "Hello, world!")
expect(post_request).to have_been_requested
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment