Skip to content

Commit

Permalink
Bring Rack::Mock cookie parsing into SPEC (fixes rack#1629)
Browse files Browse the repository at this point in the history
`#has_key?` isn't required to be supported by the object in the `headers`
element of the response coming back out of the app.  This replaces that call
with a transmogrification into a `HeaderHash` so we can use an index as
normal.  The odd `hash[] || ""` construction is necessary because
`HeaderHash#fetch` doesn't respect header name case insensitivity.
  • Loading branch information
mpalmer committed Mar 30, 2020
1 parent 026537f commit d445f04
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/rack/mock.rb
Expand Up @@ -231,9 +231,11 @@ def cookie(name)

def parse_cookies_from_header
cookies = Hash.new
if original_headers.has_key? 'Set-Cookie'
set_cookie_header = original_headers.fetch('Set-Cookie')
set_cookie_header.split("\n").each do |cookie|
hashed_headers = Rack::Utils::HeaderHash[original_headers]
if hashed_headers.has_key?("Set-Cookie")
values = (v = hashed_headers["Set-Cookie"]).respond_to?(:to_ary) ? v.to_ary : v.split("\n")

values.each do |cookie|
cookie_name, cookie_filling = cookie.split('=', 2)
cookie_attributes = identify_cookie_attributes cookie_filling
parsed_cookie = CGI::Cookie.new(
Expand Down
15 changes: 15 additions & 0 deletions test/spec_mock.rb
Expand Up @@ -324,6 +324,21 @@
res.cookie("i_dont_exist").must_be_nil
end

it "parses cookie headers provided as an array" do
res = Rack::MockRequest.new(->(env) { [200, [["set-cookie", "array=awesome"]], [""]] }).get("")
array_cookie = res.cookie("array")
array_cookie.value[0].must_equal "awesome"
end

it "parses multiple set-cookie headers provided as an array" do
cookie_headers = [["set-cookie", ["array=awesome", "multiple=times"]]]
res = Rack::MockRequest.new(->(env) { [200, cookie_headers, [""]] }).get("")
array_cookie = res.cookie("array")
array_cookie.value[0].must_equal "awesome"
second_cookie = res.cookie("multiple")
second_cookie.value[0].must_equal "times"
end

it "provide access to the HTTP body" do
res = Rack::MockRequest.new(app).get("")
res.body.must_match(/rack/)
Expand Down

0 comments on commit d445f04

Please sign in to comment.