无法通过 last_response 在 Rspec 3 中读取 cookie
我试图在 Rspec 3.1 中读取 get 调用后收到的 cookie.我看到它被返回但 last_response.cookies 不存在.如何读取响应的 cookie?
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
我知道已经有一段时间了,但现在面临完全相同的问题,经过一番挣扎,我找到了一篇文章 这里 分享了一个有趣的方法.由于我也找不到任何本地解析方法,因此对我来说效果很好.
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.
基本上,将这段代码放在您的spec/spec_helper.rb
中:
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
你可以用它来查看解析后的hash
:
and you could use this to see the parsed hash
:
puts cookies_from_response
对于 cookie 的值检查,您可以使用以下内容:
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.