ruby-on-rails – 使用Rspec v.1测试响应cookie

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用Rspec v.1测试响应cookie前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我登录我的应用程序时,服务器向我发回cookie(凭据和一些应用程序的cookie):
  1. Response sent 170 bytes of Cookie data:
  2. Set-Cookie: user_credentials=val; path=/; HttpOnly; Secure
  3.  
  4. Response sent 554 bytes of Cookie data:
  5. Set-Cookie: _app_session=otherVal; path=/; HttpOnly; Secure

…然后重定向到主页;

Cookie包括一些标志:例如httpOnly,安全等

如何测试cookie是否包含Rspec的那些标志?

至少我在哪里可以找到这些饼干?

  1. it "should generate cookies with proper flags" do
  2. params = Factory.attributes_for(:user,:username => "uname",:password => "upass"
  3. )
  4. # login
  5. post 'create',params
  6.  
  7. response.should redirect_to home_url # => pass
  8.  
  9. puts "response cookie = #{response.cookies.inspect}" # => {} // no cookies in response,why?
  10. end

解决方法

控制器规范不生成/调用真实的http请求,它们只是设置被测控制器并在其上调用所请求的操作.没有发出http请求,也没有生成真正的http答案.因此,您只能在更抽象的级别上测试Rails控制器的内部工作方式.

这些规范中的cookie处理相当简单,在这样的动作中设置cookie:

  1. def set_cookies
  2. cookies[:foo] = 'bar'
  3. cookies[:lorem] = {:value => 'ipsum',:expires => 3.days.from_now}
  4.  
  5. render :nothing => true
  6. end

导致规范中可访问以下值:

  1. it "should set some cookie values" do
  2. get :set_cookies
  3.  
  4. # response.cookies looks like this:
  5. # {'foo' => 'bar','lorem' => 'ipsum'}
  6.  
  7. response.cookies['foo'].should == 'bar'
  8. response.cookies['lorem'].should == 'ipsum'
  9. end

要测试您在响应中看到的cookie标记的类型,您必须使用能够执行真实http请求的内容.也许你可以使用水豚宝石吗?

猜你在找的Ruby相关文章