【问题标题】:Passing cookies in request spec在请求规范中传递 cookie
【发布时间】:2012-07-03 00:09:46
【问题描述】:

我在执行 GET 请求时尝试使用 rspec 2 和 rails 3 传递 cookie。

到目前为止,我已经尝试了以下方法。

get "/", {}, {"Cookie" => "uuid=10"} # cookies[:uuid] is nil
request.cookies[:uuid] = 10 # request is nil
@request.env["Cookie"] = "uuid=10" # @request is nil
helper.request.cookies[:uuid] # helper is not defined
cookies[:uuid] = 10 # cookies[:uuid] is nil
controller.cookies[:uuid] = 10 # cookies is nil

有可能吗?

【问题讨论】:

    标签: rspec rspec2 rspec-rails


    【解决方案1】:

    根据this answer,您可以在请求规范中使用cookies 方法:

    before { cookies['foo'] = 'bar' }
    

    我尝试了涉及ActionDispatch::Request.any_instance.stubs 的@phoet 解决方案,但它在 RSpec 3.4 中引发错误以及看似无关的弃用消息。

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,但我没有找到合适的解决方案。

      rspec-rails docs 状态应该是可能的:

      # spec
      request.cookies['foo'] = 'bar'
      get :some_action
      response.cookies['foo'].should eq('modified bar')
      

      在我的规范中,request 在执行 get 之前始终是 nil

      我现在正在模拟 cookie:

      before { ActionDispatch::Request.any_instance.stubs(cookies: {locale: :en}) }
      

      this guy 也有类似的问题。

      【讨论】:

      • 您链接到的文档是针对控制器规格的,而不是请求规格,这就是request 返回nil 的原因。还试图弄清楚如何在 RSpec 3.4 中做到这一点。
      【解决方案3】:

      一开始我对您是如何做到这一点感到有些困惑,但实际上这很容易。在 Rails 的 ActionDispatch::IntegrationTest 内部(或在 rspec 的情况下为 :request 规范),您可以访问 cookies 变量。

      它的工作原理是这样的:

      # set up your cookie
      cookies["fruits"] = ["apple", "pear"]
      
      # hit your endpoint
      get fruits_path, {}, {}
      
      # this works!
      expect(cookies["fruits"]).to eq(["apple", "pear"])
      

      【讨论】:

        【解决方案4】:

        在 RSpec 请求测试中对我有用的是显式传递 HTTP Cookie 标头:

          before do
            get "/api/books", headers: { Cookie: "auth=secret" }
          end
        

        【讨论】:

          【解决方案5】:

          spec/requests/some_spec.rb 中,您可以使用Rack::Test::Methods 来设置和读取cookie。

          describe 'Something' do
          
            include Rack::Test::Methods
          
            it 'can set cookies' do
              set_cookie "foo=red"
              post '/some/endpoint', params, headers
              expect(last_request.cookies[:foo]).to eq('red')
            end
          
          end
          

          文档:
          http://www.rubydoc.info/github/brynary/rack-test/Rack/MockSession#set_cookie-instance_method

          【讨论】:

            猜你喜欢
            • 2014-08-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-06-24
            • 1970-01-01
            • 2011-11-22
            • 1970-01-01
            相关资源
            最近更新 更多