设置http状态代码

redirect_to browse_path(asset.parent_id), notice: "successfully created file!", status: 201 

201是您创建资源时应设置的状态。 虽然上述方法适用于创建操作,但其操作规范不再执行:

 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期望失败:

 Expected response to be a , but was  

我接受它不再是302重定向,但它仍然将用户重定向到新路由(我想测试)。 如果我将其设置为302的“错误”代码而不是201,则redirect_to规范通过:

 redirect_to browse_path(asset.parent_id), notice: "successfully created file!", status: 302 

我应该为设置状态代码而烦恼吗? 我承认我实际上不知道浏览器如何使用它们,我的应用程序也可以正常运行,如果我在我的行动中煞费苦心地设置它们(或者只使用302重定向和200次成功)。

如果状态代码很重要,我应该如何通过上述规范?

您可以在rspec中断言response.body或其他响应属性。 在这种情况下,您所追求的是response.header["Location"]

您可以选择使用capybara / rspec来解决问题,您可以断言current_url并仍然断言状态代码。

redirect_to只是一个愚蠢的中级助手,你需要达到稍微低一级的响应水平或更高级别的水豚以获得你想要的位置。

来自文档 :

状态代码可以是标准HTTP状态代码作为整数,也可以是表示下行,下划线和符号化描述的符号。 请注意,状态代码必须是3xx HTTP代码,否则不会发生重定向。

(重点补充)

简单地说,使用201状态代码重定向是错误的。

一种方法是:

 its(:status){ should eq 201 } its(:location){ should eq 'http://test.host/' }