Rails如何计算控制器操作的响应代码?
给定以下控制器操作:
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'show' }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
Run Code Online (Sandbox Code Playgroud)
(我使用相同的视图来显示和编辑记录)
有了这个积极的测试:
test "should update basic user information" do
user = users(:jon)
user.first_name="Jonas"
put :update, :id => user.id, :merchant_user =>user.attributes
assert_response :found
user = Merchant::User.find(user.id)
assert user.first_name == "Jonas", "Should update basic user information"
end
Run Code Online (Sandbox Code Playgroud)
负面测试是这样的:
test "should not update user email for an existing email" do
user = users(:jon)
original_user_email = user.email
existing_user_email = users(:doe)
user.email=existing_user_email.email
put :update, :id => user.id, :merchant_user =>user.attributes
assert_response :success
user = Merchant::User.find(user.id)
assert user.email == original_user_email, "Should not update email for an exising one"
end
Run Code Online (Sandbox Code Playgroud)
成功更新记录会产生302响应代码,我认为GET资源/:ID的rails默认为302.无法更新记录会导致200 OK.
如何计算这些响应代码以及如何覆盖它们?
谢谢
请参阅下面的内联评论
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
# 302, the save was successful but now redirecting to the show page for updated user
# The redirection happens as a “302 Found” header unless otherwise specified.
format.json { head :no_content }
# 204, successful update, but don't send any data back via json
else
format.html { render action: 'show' }
# 200, standard HTTP success, note this is a browser call that renders
# the form again where you would show validation errors to the user
format.json { render json: @user.errors, status: :unprocessable_entity }
# 422, http 'Unprocessable Entity', validation errors exist, sends back the validation errors in json
end
Run Code Online (Sandbox Code Playgroud)
如果你看format.json { render json: @user.errors, status: :unprocessable_entity }它使用status的选项render,以更明确一些HTTP状态代码,这样你可以做render action: 'show', status: 422或者render action: 'show', status: :unprocessable_entity,如果你想(你可能没有) -和渲染默认为200 Ok(Rails使用一个符号:success别名:ok,以及
也可以看看:
看到四处访问:NOT_FOUND,:对Rails 3 INTERNAL_SERVER_ERROR等
在控制台Rack::Utils::HTTP_STATUS_CODES查看所有状态代码(该值在轨符号),即Unprocessable Entity是:unprocessable_entity
| 归档时间: |
|
| 查看次数: |
1304 次 |
| 最近记录: |