在Rails 2.3 中测试cookie

本文探讨了在Rails 2.3中测试Cookies的方法变化。介绍了如何在控制器中进行Cookies测试,并指出了无法直接测试Cookies属性的问题。
Testing Cookies in Rails 2.3

近期,我向Rails2.3移植项目的时候,遇到了一些测试cookies问题.例如,下面的Cookies用来保存访问者的用户名,Email地址,留言url信息.下面是保存cookies的语句:

cookies['blog_visitor_name'] = { :value => @comment.name, :expires => 1.year.from_now }


上面的cookies赋值是属于扩展模式,要设置哈希表的值对,还要设置过期时间.下面的描述是最简单的cookies设置:
 cookies['cookie_name] = 'cookie_value'

这种设置和读取cookies的方式在Rails2.3中并没有什么改变.改变的是测试cookies的方式.在Rails2.3之前,你需要为每一个request cookie创建一个CGI::Cookie对象,当请求发送后,cookie创建了,你就可以通过cookies的accessor用assert断言来验证cookies的属性了.这是Rails2.3之前的方式
例子如下:
 def test_comment_creation_overwrites_visitor_cookies
@request.cookies['blog_visitor_name'] = CGI::Cookie.new('blog_visitor_name', 'Fred F.')
post :create, { ... }
assert_equal 'Fred', cookies['blog_visitor_name'].value
assert_equal '/', cookies['blog_visitor_name'].path
assert cookies['blog_visitor_name'].expires > 364.days.from_now
end


上面代码,演示了测试cookies的之前用法.先创建一个CGI:Cookie对象.执行创建请求,生成对应的cookies并把Fred F做为名字.当请求执行,就可以通过断言来验证cookies了.这是之前的方式.

对于Fails2.3, cookies测试的用法改成在Controller中执行.

 def test_comment_creation_overwrites_visitor_cookies
@request.cookies['blog_visitor_name'] = 'Fred F.'
post :create, { ... }
assert_equal 'Fred', cookies['blog_visitor_name']
assert_equal '/', cookies['blog_visitor_name']...???
assert cookies['blog_visitor_name']...??? > 364.days.from_now
end



cookies的赋值和上面的情况不一样了,更像使用controller.

[quote]Since the cookies accessor now returns the cookie value only (like in controllers), it is easier to test wether a cookie was correctly set to the expected value. However, extended information like the cookie path and the expiration time are not available anymore and therefore we cannot test anymore if these attributes were correctly set by the controller.

So how can you test cookie attributes with Rails 2.3? Unfortunately you can’t. The cookies accessor in tests parses the content of the Set-Cookie header of a response and builds a hash of cookies which were set by the controller action. Unfortunately, it only gathers the cookie name and value and does not parse the rest of the data. The only way that I know of to test cookie attributes is to manually parse the contents of the Set-Cookie header for now.[/quote]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值