在请求规范中传递cookie

Lin*_*der 7 rspec rspec2 rspec-rails

我正在尝试使用rspec 2和rails 3在执行GET请求时传递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
Run Code Online (Sandbox Code Playgroud)

可能吗?

小智 9

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

  before do
    get "/api/books", headers: { Cookie: "auth=secret" }
  end
Run Code Online (Sandbox Code Playgroud)


Chr*_*ers 7

根据此答案,您可以cookies在请求规范中使用该方法:

before { cookies['foo'] = 'bar' }
Run Code Online (Sandbox Code Playgroud)

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


and*_*kle 5

我一开始对你是如何做到这一点感到有点困惑,但实际上非常简单。在 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"])
Run Code Online (Sandbox Code Playgroud)


pho*_*oet 4

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

rspec-rails 文档指出这应该是可能的:

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

在我的规范中request总是nil在执行 get 之前。

我现在正在嘲笑饼干:

before { ActionDispatch::Request.any_instance.stubs(cookies: {locale: :en}) }
Run Code Online (Sandbox Code Playgroud)

这家伙也有类似的问题。

  • 您链接到的文档适用于控制器规范,而不是请求规范,这就是“request”返回“nil”的原因。还试图弄清楚如何在 RSpec 3.4 中做到这一点。 (2认同)