我还是不熟悉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
答案 0 :(得分:2)
ActionController :: UrlGenerationError:没有路由匹配 {:action =>“ show”,:company_id =>功能编号:1,版本:1,名称: “ MyText”,company_id:1,created_at:“ 2018-10-17 18:34:14”, Updated_at:“ 2018-10-17 18:34:14”,total_stocks_in_company:无, :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