201 是您创建资源时应设置的状态.虽然上述方法适用于创建操作,但其操作的规范不再适用:
201 is the status you should set if you've created a resource. While the above method works for a create action, the spec for its action no longer does:
subject { response } describe '.create' do context 'when orphan' do before do post :create, asset: { parent_id: nil, uploaded_file: file } end it { should have_http_status 201 } it { should redirect_to '/' } end end状态期望通过,但redirect_to期望失败:
The status expectation passes, but the redirect_to expectation fails:
Expected response to be a <redirect>, but was <201>我接受它不再是 302 重定向,但它仍然将用户重定向到新路由(我想测试).如果我将其设置为 302 而不是 201 的错误"代码,则 redirect_to 规范通过:
I accept that it's no longer a 302 redirect, but it does still redirect the user to a new route (which I want to test). The redirect_to spec passes if I set it to the "wrong" code of 302, rather than 201:
redirect_to browse_path(asset.parent_id), notice: "successfully created file!", status: 302那么我应该为设置状态代码而烦恼吗?我承认我实际上不知道浏览器如何使用它们,如果我在我的操作中煞费苦心地设置它们或不设置它们(只需使用 302 重定向和 200 次成功),我的应用程序也能正常运行.
so should I bother with setting status codes? I'll admit I actually have no idea how the browser uses them and my applications functions just as well if I painstakingly set them in my actions or don't (just use 302 redirects and 200 successes).
如果状态代码很重要,我应该如何让上述规范通过?
If status codes are important, how should I get my above specs to pass?
推荐答案您可以在 rspec 中断言 response.body 或其他响应属性.在这种情况下,您所追求的是 response.header["Location"]
You can assert off response.body or other response attributes within rspec. In this case the thing you are after is response.header["Location"]
您可以选择使用 capybara/rspec 来避免问题,您可以在其中断言 current_url 并仍然断言状态代码.
You can choose to dodge the problem with capybara/rspec where you can assert current_url and still assert the status code.
redirect_to 只是一个愚蠢的中级助手,你需要在响应中达到稍低的级别.水豚的东西或更高的级别才能到达你想去的地方.
redirect_to is just a dumb mid level helper and you need to reach to a slightly lower level in response.something or higher level with capybara to get where you want to be.
更多推荐
设置http状态码
发布评论