Quite a bit of my old code just redirects when an action gets a request with an unsupported method, for example; 'get' requests to 'destroy' actions. While my old approach prevented anything bad from happening it always seemed wrong. It also made maintaining my tests a tiny bit more complicated because each seemed to have a different location they redirected to.
So I decided to clean up the code in my current project today. The obvious choice was to render an error template and return the proper status code.
This also simplified my tests.
# file: app/controllers/parts_controller.rb
def destroy
unless request.delete?
render :layout => false, :template => "errors/405", :status => 405
return
end
begin
Part.find(params[:id]).destroy
flash.now[:success] = "The part has been successfully deleted."
rescue
flash[:failure] = "Unable to delete part."
end
end
# file: test/functional/parts_controller_test.rb
def test_destroy_get
get :destroy
assert_response 405
assert_template("errors/405")
end
No comments:
Post a Comment