Rails如何計算控制器操作的響應代碼?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
(我使用的是相同的視圖來顯示和編輯記錄)
有了這個積極的測試:
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
而且一負面測試是這樣的:
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
成功更新記錄會導致一個302響應代碼,我假設rails資源/:ID的缺省值爲302。無法更新記錄導致200 OK。
這些響應代碼是如何計算的?我如何覆蓋它們?
感謝
有是HTML和JSON請求返回的不同代碼。我認爲200 OK會返回保存錯誤,以確保與瀏覽器行爲的兼容性。 –