在routes.rb
我有:
resources :themes do
resources :messages
end
在messages_controller_test.rb
我有:
setup do
@theme = themes(:one)
@message = messages(:one)
end
test "should create message" do
assert_difference('Message.count') do
post :create, message: { title: "Title", body: "Some body", theme_id: @theme.id }
end
assert_redirected_to theme_path(@theme)
end
我收到错误:Couldn't find Theme without an ID
出了什么问题?
答案 0 :(得分:3)
使用嵌套资源,创建路径如下所示:
/themes/:theme_id/messages
所以你需要传递这些参数:
test "should create message" do
assert_difference('Message.count') do
post :create, {theme_id: @theme.id, message: { title: "Title", body: "Some body", theme_id: @theme.id }}
end
assert_redirected_to theme_path(@theme)
end
实际上在你的控制器动作中你可以处理:theme_id param以便不再在params中传递它[:message]