Minitest Rails测试用例中异常URL的点符号含义排查
Rails测试重定向URL异常:点符号问题解析
错误信息
AnswersControllerTest#test_should_destroy_answer [/Users/pitosalas/mydev/questionanswer/test/controllers/answers_controller_test.rb:47]: Expected response to be a redirect to <http://www.example.com/questions/525858932> but was a redirect to <http://www.example.com/questions.525858932>. Expected "http://www.example.com/questions/525858932" to be === "http://www.example.com/questions.525858932".
测试代码
test "should destroy answer" do assert_no_difference("Question.count") do delete question_answer_url(@question, @answer) end assert_redirected_to question_url(@question) end
控制器代码
def destroy @question = Question.find(params[:question_id]) @answer = Answer.find(params[:id]) respond_to do |format| format.html do if !@answer.comments.empty? redirect_to questions_url(@question), notice: "First delete all the comments" elsif @answer.destroy redirect_to questions_url(@question), notice: "Answer was successfully destroyed." else redirect_to questions_url(@question), notice: "Answer could not be destroyed." end end format.json { head :no_content } end end
问题解析
URL里的点符号是路由辅助方法使用错误导致的:
- 控制器中用了复数形式的
questions_url,这个方法对应问题列表页的路由(/questions)。当你向它传入@question实例时,Rails会把实例ID识别为格式后缀(类似.html这类格式参数),因此生成了questions.525858932这种错误路径。 - 测试代码里用的
question_url(@question)是单数形式,对应单个问题详情页的路由(/questions/:id),能正确生成带斜杠的标准路径。
修复方法
把控制器中所有的redirect_to questions_url(@question)替换成redirect_to question_url(@question),或者直接写redirect_to @question(Rails会自动推断出对应的单个资源路由)。
内容的提问来源于stack exchange,提问作者pitosalas
相关产品推荐
相关产品推荐

