在为 Ruby on Rails 应用程序(Rails 版本 6.0.6)搭建新模型后,我对新模型的新视图(索引、显示、新建和编辑)进行了几个搭建的 Rspec 测试。我仔细检查了应用程序运行时所有这些视图的功能是否没有问题,但在添加更新 Rspec 测试(主要是使用 FactoryBot 添加)后,我只能使显示和索引页面测试正常工作。新页面和编辑页面测试均因路由问题而失败。
我们已经为新模型(我们称之为模型
Organization
)定义了范围的路由:
scope '/:fiscal_year' do
resources :organization, shallow: true
end
我对编辑页面的更新测试为:
require 'rails_helper'
RSpec.describe 'organizations/edit' do
let(:organization) { create(:organization) }
before do
assign(:organization, organization)
assign(:fiscal_year, OrganizationFiscalYear::CURRENT_FISCAL_YEAR)
end
it 'renders the edit organization form' do
render
assert_select 'form[action=?][method=?]', organization_path(organization),
'post' do
assert_select 'input[name=?]', 'organization[name]'
end
end
end
编辑和新页面的
_form
的开头为:
= form_for organization do |f|
...
不幸的是,规格测试在
render
行失败,并显示以下消息:
Failures:
1) organizations/edit renders the edit organization form
Failure/Error: = form_for organization do |f|
ActionView::Template::Error:
No route matches {:action=>"show", :controller=>"organizations", :fiscal_year=>#<Organization id: 1, name: "Blah Blah", created_at: "2023-12-22 20:37:45", updated_at: "2023-12-22 20:37:45">}, missing required keys: [:id]
堆栈跟踪指向
_form.html.haml
中的第 1 行,因此我可以判断是 form_for
生成了错误。
我一生都无法弄清楚为什么这会产生路由错误。我已经三次检查了编辑和新功能的视图,并且 Rails 服务器没有任何路由错误。我在规格测试中缺少什么?
测试对我来说似乎是正确的,而你自己的开发检查似乎是错误的。
form_for organization
需要提供 fiscal_year
才能构建适当的更新路径。应该是 form_for [fiscal_year, organization]
,您只提供 organization
的事实就是您的错误显示 :fiscal_year=>#<Organization id: 1, ...>
参数的原因。