Open grjones opened 1 year ago
Hi, thank you for reporting the issue.
There might be problems on Faraday::Utils::Headers
; it can't handle Symbol
header including -
here.
Also, testing adapter does not type-cast non-String
body as String
, so stub.post('/api/push', {}, headers)
should be stub.post('/api/push', '{}', headers)
(I think testing adapter can cast the value 😅 )
I think you don't have to explicitly set Content-Type
in the block of Faraday.new
. Instead, the workaround is like this:
headers = { 'Content-Type' => 'application/json' }
client.adapter(:test) do |stub|
stub.post('/api/push', '{}', headers) { [200, {}, {}] }
stub.strict_mode = true
end
Here is the change:
diff --git a/a.rb b/a.rb
index a0a1cba..ef6599a 100644
--- a/a.rb
+++ b/a.rb
@@ -1,6 +1,6 @@
-headers = { 'Content-Type': 'application/json' }
+headers = { 'Content-Type' => 'application/json' }
client.adapter(:test) do |stub|
- stub.post('/api/push', {}, headers) { [200, {}, {}] }
+ stub.post('/api/push', '{}', headers) { [200, {}, {}] }
stub.strict_mode = true
end
Hi @yykamei. Yes, that also works. The bug though is that you'd want request(:json)
to be able to work, which should be taking care of encoding the request body as json and setting the correct content-type. So, yours is also a workaround but without the request(:json)
, you'll need to encode as json your self. Eg:
stub.post('/api/push', payload.to_json, headers) { [200, {}, {}] }
Actually, we're both partly right. It is indeed that symbols aren't supported in the testing framework. So your headers change works. But, f.request(:json)
also works. So, my working version is:
client = Faraday.new(url: <your_base_url>) do |f|
f.request(:json)
end
headers = { 'Content-Type' => 'application/json' } # no longer a symbol
client.adapter(:test) do |stub|
stub.post('/api/push', {}, headers) { [200, {}, {}] }
stub.strict_mode = true
end
Thanks for your help. I don't know if this should just be closed? Maybe others would get tripped up by the symbol comparison.
Maybe, I understood your point; the testing adapter should consider the JSON middleware when comparing the actually used request header with expected one. If developers use request(:json)
, testing adapter should also encode the passed stub body as JSON. Is it correct?
Basic Info
Issue description
When adding rspec tests using Faraday's test facility, an error is falsely raised when the following are true:
request(:json)
is set'Content-Type': 'application/json'
is set in a:test
adapter stubuse_strict = true
is set in the:test
adapterverify_stubbed_calls
is calledThe resulting error is:
This appears to be due to inconsistent header case normalization and case sensitive header matching in strict stubs.
Explicitly setting the
Content-type
header (with lowercase-type
) is a workaround like so:Steps to reproduce
Create a faraday object like so:
Set the expected stubs:
Use the client:
Run
verify_stubbed_calls
and observe the unexpected failure: