respond_with and redirects on error

Hello,

I'm using edge Rails and I have the following code in my users controller, with the respective test:

  def update     @user = User.find(params[:id])     if @user.update_attributes(params[:user])       flash[:notice] = t :user_successfully_updated     end     respond_with(@user)   end

  test "should not update user if modifications are invalid" do     put :update, :id => users(:foo).id, :user => {:name => nil}     assert !assigns(:user).valid?     assert_redirected_to edit_user_url(users(:foo))   end

The last assertion fails, saying the response is a 200 instead of a redirect. From the information I found online about reponds_to, it seems that a redirection to the edit action should have been done, given that the object is invalid, but that isn't the case in this test. Am I missing something obvious here?

Thanks in advance, Andre

andrenth@gmail.com wrote:

The last assertion fails, saying the response is a 200 instead of a redirect.

Standard rails behaviour is not to redirect if the update fails.

If you redirect on failure, the submitted modifications in the form gets over-written. So say you modify a blog altering a large paragraph of your master work. However, you also accidentally delete the blog title and that causes a validation failure. What you want then is for the rendered form to contain the data you submitted, not the content as it is in the database. Redirecting to edit will pull the data from the database again and populate the form with that, thereby losing the changes the user is trying to submit.

Also you'll get a fresh object - one without the error data. So you won't have anything to populate the error report with. What needs to be passed back to the form, is the same object that failed to save.

That's one of the down sides of separating the edit and update methods - because you end up with both having to be able to handle the form rendering.

Got it, thanks!