You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5.1.5控制器show动作测试报错:缺少必填键[:id]求助

Rails 5.1.5 Posts控制器show动作测试报错:缺少必填键[:id]

我最近在用Rails 5.1.5搭配默认测试框架写Posts控制器的测试时卡壳了——index动作的测试跑起来完全没问题,但一测show动作就报错说缺少必填键[:id]。我自己折腾了两天,试了各种调整还是没解决,实在没办法了,来求助各位大佬!

以下是我相关文件的内容和测试报错信息:

相关文件内容

posts_controller_test.rb

require 'test_helper'

class PostsControllerTest < ActionDispatch::IntegrationTest
  test "should get show" do
    get posts_show_url
    assert_response :success
  end
end

posts.yml(fixtures文件)

one:
  title: "First Post"
  body: "This is my first test post."

two:
  title: "Second Post"
  body: "Another test post content."

routes.rb

Rails.application.routes.draw do
  resources :posts
  # 其他项目路由...
end

posts_controller.rb

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end
end

测试控制台报错信息

Error:
PostsControllerTest#test_should_get_show:
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"posts"} missing required keys: [:id]
    test/controllers/posts_controller_test.rb:6:in `block in <class:PostsControllerTest>'

我自己试过的操作

  • 检查了routes.rb里的路由配置,确认resources :posts已经正确添加
  • 手动在浏览器里访问/posts/1能正常打开show页面,说明生产环境的路由没问题
  • 试过在测试里硬编码get '/posts/1',测试能通过,但用路由助手就不行

有没有大佬能帮我看看问题出在哪?感激不尽!

内容的提问来源于stack exchange,提问作者Kizlo kizlo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:16:44