ActionController::UrlGenerationError: No route matches and missing id even though I am passing the id to the test

ActionController::UrlGenerationError: No route matches and missing id even though I am passing the id to the test

我还是 rails 的新手,正在尝试为我的一个控制器编写一些基本测试。

为了让这个问题保持简短,让我们看一下我的两个测试。

从下面的错误中,我可以看到 missing required keys: [:id] 问题,但我正在传递 id - 所以我无法弄清楚问题是什么。

感谢任何帮助:)

测试文件(只收录了本题的相关测试)

require 'test_helper'

class CaptablesControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  setup do
    @captable = captables(:one)
  end

  setup do
    @company = companies(:one) 
  end

  setup do 
    @user = users(:one) 
  end

  test "should show captable" do
    sign_in @user
    get company_captable_url(@captable), id: @captable.id
    assert_response :success
  end

  test "should get index" do
    sign_in @user
    get company_captables_url(@company)
    assert_response :success
  end
....

控制器(只包含相关方法)

class CaptablesController < ApplicationController
  before_action :set_company
  before_action :set_captable, only: [:show, :edit, :update, :destroy]

  def index
    @captables = @company.captables
  end

  def show
    @captable = Captable.find(params[:id])
  end
.....

上限表夹具

one:
  id: 1
  version: 1
  name: MyText
  company_id: 1

这是尝试 运行 测试时的错误

Error:
    CaptablesControllerTest#test_should_show_captable:
    ActionController::UrlGenerationError: No route matches {:action=>"show", :company_id=>#<Captable id: 1, version: 1, name: "MyText", company_id: 1, created_at: "2018-10-17 18:34:14", updated_at: "2018-10-17 18:34:14", total_stocks_in_company: nil>, :controller=>"captables"}, missing required keys: [:id]
        test/controllers/captables_controller_test.rb:41:in `block in <class:CaptablesControllerTest>'


    bin/rails test test/controllers/captables_controller_test.rb:39

ActionController::UrlGenerationError: No route matches {:action=>"show", :company_id=>Captable id: 1, version: 1, name: "MyText", company_id: 1, created_at: "2018-10-17 18:34:14", updated_at: "2018-10-17 18:34:14", total_stocks_in_company: nil, :controller=>"captables"}, missing required keys: [:id]

我认为您的路径助手 company_captable_url 是使用 嵌套资源 构建的。因此它需要两个动态段的值,即 :company_id:id。所以 @company 应该和 @captable 一起传递。您需要将其更改为以下

test "should show captable" do
  sign_in @user
  get company_captable_url(@company, @captable)
  assert_response :success
end