RSpec 中 response 和 last_response 的区别

Gio*_*ssi 1 ruby-on-rails rspec-rails

我有一个测试,检查请求的页面是否返回 200 状态代码:

expect(response).to have_http_status(:success)
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用以下测试明确返回不同的状态代码:

return render json: { error: 'error message' }, status: :unprocessable_entity
Run Code Online (Sandbox Code Playgroud)

它仍然通过。

为什么responselast_response具有不同的状态:

response.status      # 200
last_response.status # 422
Run Code Online (Sandbox Code Playgroud)

Jam*_*ani 6

response由 提供ActionController::TestCase

文档

一个 ActionDispatch::TestResponse 对象,表示最后一个 HTTP 响应的响应。

作为参考,这里是控制器测试的 rspec 文档。这可能有助于弄清楚response应该如何使用。


last_response 来自 Rack::MockResponse < Rack::Response

文档

返回会话中收到的最后一个响应。如果尚未发送任何请求,则引发错误。


在您的测试用例中,您可能使用了一种允许模拟访问页面的方法。这将设置你response.status200为你做了成功的请求。如果您随后使用 Rack 来刺激端点,例如:

put '/users', {my_user: 'blah'}
Run Code Online (Sandbox Code Playgroud)

并且您使用不正确的参数执行此操作,那么您last_response.status将是422.

最终,混乱归结之间的命名的相似性ActionControllerRack::MockResponse,这我同意是相当混乱。