我可以在不提供显式外键的情况下测试嵌套资源吗?
我正在尝试修复嵌套资源的功能测试。我的 config/routes.rb 文件如下所示:
Shop360::Application.routes.draw do
resources :libraries do
resources :library_imports
end
end
嵌套library_imports 资源会破坏生成的测试,如下所示:
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:library_imports)
end
因为嵌套会更改所有 URL。
我在几个地方看到了通过添加 library_id
参数来解决此问题的建议,如下所示:(
test "should get index" do
get :index, :library_id => 1
assert_response :success
assert_not_nil assigns(:library_imports)
end
第二行已更改)
因此,为了使其正常工作,我必须显式指定 library_id
代码> 在我的library_import 夹具中?自 Rails 2.0 以来,无需借助这些显式键定义就可以在夹具数据中定义关联。我现在是不是因为在筑巢资源而被迫回到这个老鼠窝里?
难道没有更好的方法让我的测试通过吗?
I'm trying to fix my functional tests for a nested resource. My config/routes.rb
file looks like this:
Shop360::Application.routes.draw do
resources :libraries do
resources :library_imports
end
end
Nesting the library_imports
resources breaks generated tests like this one:
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:library_imports)
end
because nesting changes all the URLs.
I've seen advice in several places to fix this by adding a library_id
parameter like so:
test "should get index" do
get :index, :library_id => 1
assert_response :success
assert_not_nil assigns(:library_imports)
end
(second line changed)
So to get this to work, I have to explicitly specify a library_id
in my library_import fixture? It's been possible since Rails 2.0 to define associations in the fixture data without resorting to these explicit key definitions. Am I now being forced back into this rat's nest because I'm nesting resources?
Is there not a better way to get my test to pass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,这并不像我想象的那么复杂。让我们从固定装置开始:
libraries.yml
library_imports.yml
我以正确的方式在此固定装置数据中创建关联(即没有显式键)。
现在,回想一下失败的测试(在library_imports_controller_test.rb中):
该文件的顶部是设置回调,如下所示:
因此我可以在测试中引用@library_import(特别是其library_id字段)。我这样改变它:
我的测试从红色变为绿色。
OK, this wasn't as complicated as I thought. Let's start with the fixtures:
libraries.yml
library_imports.yml
I create associations in this fixture data the proper way (i.e. no explicit keys).
Now, recall the failing test (in library_imports_controller_test.rb):
At the top of this file is the setup callback which looks like this:
So I can refer to @library_import (and specifically its library_id field) in my test. I change it like so:
And my test goes from red to green.
您是否尝试过在夹具文件中定义关系?
Have you tried defining the relationship in the fixture files?