Ruby on rails 如何在rails中测试嵌套属性?

Ruby on rails 如何在rails中测试嵌套属性?,ruby-on-rails,testing,functional-testing,Ruby On Rails,Testing,Functional Testing,我有一个rails控制器,定义如下: 在页面上,用户可以通过发布嵌套属性来指定行项目的数量。参数如下所示: { "cart" => { "line_items_attributes" => { "0" => { "quantity" => "2", "id" => "36" } } }, "commit" => "Update Cart", "authenticity_token" => "UdtQ+lchS

我有一个rails控制器,定义如下:

在页面上,用户可以通过发布嵌套属性来指定行项目的数量。参数如下所示:

{ "cart" => {
  "line_items_attributes" => {
    "0" => {
      "quantity" => "2",
      "id" => "36" } } },
  "commit" => "Update Cart",
  "authenticity_token" => "UdtQ+lchSKaHHkN2E1bEX00KcdGIekGjzGKgKfH05So=",
  "utf8"=>"\342\234\223" }
@cart.update_attributes(params[:cart])
it "should accept nested attributes for units" do
  expect {
    Cart.update_attributes(:cart => {:line_items_attributes=>{'0'=>{'quantity'=>2, 'other_attr'=>"value"}})
  }.to change { LineItems.count }.by(1)
end
在我的控制器操作中,这些参数保存如下:

{ "cart" => {
  "line_items_attributes" => {
    "0" => {
      "quantity" => "2",
      "id" => "36" } } },
  "commit" => "Update Cart",
  "authenticity_token" => "UdtQ+lchSKaHHkN2E1bEX00KcdGIekGjzGKgKfH05So=",
  "utf8"=>"\342\234\223" }
@cart.update_attributes(params[:cart])
it "should accept nested attributes for units" do
  expect {
    Cart.update_attributes(:cart => {:line_items_attributes=>{'0'=>{'quantity'=>2, 'other_attr'=>"value"}})
  }.to change { LineItems.count }.by(1)
end
但我不知道如何在测试中测试这种行为
@cart.attributes
仅生成模型属性,而不是嵌套属性


如何测试这种行为?如何在我的功能测试中使用嵌套属性模拟post请求?

使用嵌套属性更新购物车后,您可以通过执行以下操作来访问嵌套属性

@cart.line_items

在Rails3中使用
test/unit
,首先生成集成测试:

rails g integration_test cart_flows_test
在包含测试的生成文件中,类似于:

test "if it adds line_item through the cart" do
  line_items_before = LineItem.all
  # don't forget to sign in some user or you can be redirected to login page
  post_via_redirect '/carts', :cart => {:line_items_attributes=>{'0'=>{'quantity'=>2, 'other_attr'=>"value"}}}

  assert_template 'show'
  assert_equal line_items_before+1, LineItem.all
end

我希望这会有所帮助。

假设您使用的是Test::Unit,并且您在设置中的@cart中有一个购物车,请在更新测试中尝试以下操作:

cart_attributes = @cart.attributes
line_items_attributes = @cart.line_items.map(&:attributes)
cart_attributes[:line_items] = line_items_attributes
put :update, :id => @cart.to_param, :cart => cart_attributes

派对有点晚了,但你不应该在控制器上测试这种行为。嵌套属性是模型行为。控制器只是将任何内容传递给模型。在控制器示例中,没有提到任何嵌套属性。您希望测试是否存在由模型中的
接受
的嵌套属性所创建的行为

您可以使用rSpec进行如下测试:

{ "cart" => {
  "line_items_attributes" => {
    "0" => {
      "quantity" => "2",
      "id" => "36" } } },
  "commit" => "Update Cart",
  "authenticity_token" => "UdtQ+lchSKaHHkN2E1bEX00KcdGIekGjzGKgKfH05So=",
  "utf8"=>"\342\234\223" }
@cart.update_attributes(params[:cart])
it "should accept nested attributes for units" do
  expect {
    Cart.update_attributes(:cart => {:line_items_attributes=>{'0'=>{'quantity'=>2, 'other_attr'=>"value"}})
  }.to change { LineItems.count }.by(1)
end

如何访问嵌套属性我知道,但我不知道如何在功能测试中使用嵌套属性模拟post请求。Cart.update\u属性不起作用,因为它应该在Cart实例上调用,而不是在Cart本身上调用。