无法通过 last_response 在 Rspec 3 中读取 cookie [英] Unable to read cookie in Rspec 3 via last_response

查看:37
本文介绍了无法通过 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.

这篇关于无法通过 last_response 在 Rspec 3 中读取 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆