gil*_*las 8 ruby-on-rails ruby-on-rails-3
我正在使用TestUnit,我想测试记住我的功能(当用户登录时).
cookies变量(以及require/response .cookies)仅包含没有过期时间的cookie值.
当cookie应该过期时,Rails会以某种方式告诉Web浏览器,因此我认为必须有一种方法来检查cookie过期时间.
test "set permanent cookie" do
post :create, email: 'email', password: 'password', remember_me: true
# cookies[:auth_token] = random_string
# @request.cookies[:auth_token] = also_random_string
# @response.cookies[:auth_token] = also_random_string
end
Run Code Online (Sandbox Code Playgroud)
问题是我只能得到cookie的值而不是包含过期时间的哈希值.
正如您所注意到的,cookies当您在调用后检查哈希时,哈希仅包含值,而不包含过期时间post(至少从 Rails 2.3 开始就是这种行为)。
您有两个选择:
首先,您可以检查该response.headers["Set-Cookie"]物品。它将包括其中的到期时间。但是,该Set-Cookie值只是一个字符串,您需要对其进行解析。例如,cookies["foo"] = {:value => "bar", :expires => Time.now + 10.years }会给你:
response.headers["Set-Cookie"]
# => "foo=bar; path=/; expires=Mon, 16-Aug-2021 21:54:30 GMT"
Run Code Online (Sandbox Code Playgroud)
另一个选项(取自This Question/Answer)是存根 cookie jar 并确保向其发送一个expires值:
stub_cookie_jar = HashWithIndifferentAccess.new
controller.stub(:cookies) { stub_cookie_jar }
post :create, email: 'email', password: 'password', remember_me: true
expiring_cookie = stub_cookie_jar['expiring_cookie']
expiring_cookie[:expires].to_i.should be_within(1).of(1.hour.from_now.to_i)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1813 次 |
| 最近记录: |