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)
它仍然通过。
为什么response和last_response具有不同的状态:
response.status # 200
last_response.status # 422
Run Code Online (Sandbox Code Playgroud)
response由 提供ActionController::TestCase。
从文档:
一个 ActionDispatch::TestResponse 对象,表示最后一个 HTTP 响应的响应。
作为参考,这里是控制器测试的 rspec 文档。这可能有助于弄清楚response应该如何使用。
last_response 来自 Rack::MockResponse < Rack::Response
从文档:
返回会话中收到的最后一个响应。如果尚未发送任何请求,则引发错误。
在您的测试用例中,您可能使用了一种允许模拟访问页面的方法。这将设置你response.status要200为你做了成功的请求。如果您随后使用 Rack 来刺激端点,例如:
put '/users', {my_user: 'blah'}
Run Code Online (Sandbox Code Playgroud)
并且您使用不正确的参数执行此操作,那么您last_response.status将是422.
最终,混乱归结之间的命名的相似性ActionController和Rack::MockResponse,这我同意是相当混乱。
| 归档时间: |
|
| 查看次数: |
2420 次 |
| 最近记录: |