From 00574dd6e480b283b1698f407b2d23bd17efc8c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Bu=CC=88nemann?= Date: Sat, 21 Jul 2018 15:22:44 +0200 Subject: [PATCH] Fix KeyError with missing Host in HTTP::Request When calling `HTTP::Client#exec` with an `HTTP::Request` instance the Host header is not automatically filled by the http client, so we need to add it manually or the `host_matches?` check in the stub will fail with a `KeyError` exception. --- spec/webmock_spec.cr | 10 ++++++++++ src/webmock/core_ext.cr | 1 + 2 files changed, 11 insertions(+) diff --git a/spec/webmock_spec.cr b/spec/webmock_spec.cr index 3533acc..80fb643 100644 --- a/spec/webmock_spec.cr +++ b/spec/webmock_spec.cr @@ -341,6 +341,16 @@ describe WebMock do end end + it "works with exec" do + WebMock.wrap do + WebMock.stub(:get, "http://www.example.com") + + client = HTTP::Client.new "www.example.com" + request = HTTP::Request.new("GET", "/") + client.exec request + end + end + describe ".calls" do it "returns 0 by default" do WebMock.wrap do diff --git a/src/webmock/core_ext.cr b/src/webmock/core_ext.cr index dee00cf..89e1229 100644 --- a/src/webmock/core_ext.cr +++ b/src/webmock/core_ext.cr @@ -8,6 +8,7 @@ end class HTTP::Client private def exec_internal(request : HTTP::Request) request.scheme = "https" if tls? + request.headers["Host"] = host_header unless request.headers.has_key?("Host") stub = WebMock.find_stub(request) return stub.exec(request) if stub