嵌套控制器动作测试

时间:2012-03-29 11:23:34

标签: ruby-on-rails ruby-on-rails-3 testing

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

出了什么问题?

1 个答案:

答案 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]