1

我对 Rails 还是很陌生,并试图为我的一个控制器编写一些基本测试。

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

  • should show captable失败
  • should get index asserts成功地

从下面的错误中,我可以看到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
4

1 回答 1

2

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”},缺少必需的键:[: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
于 2018-10-17T18:51:09.073 回答