Unable to read cookie in Rspec 3 via last_response
Asked Answered
R

1

1

I am trying to read in Rspec 3.1 a cookie received after get call. I see it is returned but the last_response.cookies doesn't exist. How can I read response's cookie?

  it "doesn't signs in" do
    get '/ui/pages/Home'
    puts last_response.cookies
  end
Roadbed answered 15/3, 2015 at 14:47 Comment(7)
Could you add the code you are using at the moment causing you unexpected value returned?Og
Have you checked the another answer in SO? It might help. Good luck!Og
I need the responses's cookies not requestRoadbed
I rather meant this: rack_mock_session.cookie_jar. It the answer provided it seems the value is set on response with: response.set_cookie "foo", :value => "bar"Og
Tried it. it has empty cookies[]Roadbed
Could you add the code of your action that tries to set the cookie? Which version of Sinatra do you use?Og
The cookies do exist in the last_response. however in a set-cookie header. I want that parsed. how can I do thatRoadbed
S
0

I know it has been a while, but facing exactly this same issue now, after some struggle, I've found an article here that shares an interesting approach. As I also couldn't find any native parsed method for this, that has worked fine for me.

Basically, place this piece of code below on your spec/spec_helper.rb:

def cookies_from_response(response=last_response)
  Hash[response["Set-Cookie"].lines.map { |line|
    cookie = Rack::Test::Cookie.new(line.chomp)
    [cookie.name, cookie]
  }]
end

and you could use this to see the parsed hash:

puts cookies_from_response

For a cookie's value check, you could then use something like:

# Given your cookie name is 'foo' and the content is 'bar'
expect(cookies['foo'].value).to eq 'bar'

Hopefully this becomes helpful to others facing similar issues.

Semiconductor answered 26/4, 2017 at 1:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.