2011-03-12 23 views
7

我有一個滑軌控制器,定義如下:如何在rails中測試嵌套屬性?

https://github.com/abonec/Simple-Store/blob/master/app/controllers/carts_controller.rb

cart頁面,用戶可以通過發佈嵌套屬性指定line_items的數量。參數如下所示:

{ "cart" => { 
    "line_items_attributes" => { 
    "0" => { 
     "quantity" => "2", 
     "id" => "36" } } }, 
    "commit" => "Update Cart", 
    "authenticity_token" => "UdtQ+lchSKaHHkN2E1bEX00KcdGIekGjzGKgKfH05So=", 
    "utf8"=>"\342\234\223" } 

在我的控制器操作這些PARAMS保存這樣的:

@cart.update_attributes(params[:cart]) 

但我不知道如何在測試測試此行爲。 @cart.attributes只生成模型屬性不嵌套的屬性。

我該如何測試這種行爲?如何在我的功能測試中使用嵌套屬性模擬post請求?

回答

0

在更新與嵌套屬性的車,你可以通過做

@cart.line_items 
+0

如何訪問到我知道嵌套的屬性,但我不知道如何在功能測試中模擬嵌套屬性的post請求。 – abonec 2011-03-13 09:02:01

1

使用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 

我希望幫助。

3

假設你正在使用測試::單位,你必須在安裝@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 
5

有點遲到了,但你不應該從控制器測試這種行爲。嵌套屬性是模型行爲。控制器只是將任何東西傳遞給模型。在您的控制器示例中,沒有提及任何嵌套屬性。你想測試通過accepts_nested_attributes_for在模型中創建的行爲存在

你可以這樣使用RSpec測試:

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