【问题标题】:How to testing nested attributes in rails?如何测试rails中的嵌套属性?
【发布时间】:2011-03-12 17:41:30
【问题描述】:

我有一个 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" }

在我的控制器操作中,这些参数是这样保存的:

@cart.update_attributes(params[:cart])

但我不知道如何在测试中测试这种行为。 @cart.attributes 只生成模型属性,不生成嵌套属性。

如何测试这种行为?如何在我的功能测试中模拟带有嵌套属性的发布请求?

【问题讨论】:

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


    【解决方案1】:

    聚会有点晚了,但您不应该从控制器测试该行为。嵌套属性是模型行为。控制器只是将任何东西传递给模型。在您的控制器示例中,没有提及任何嵌套属性。您想测试模型中 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
    

    【讨论】:

    • Cart.update_attributes 不起作用,因为它应该在 Cart 的实例而不是 Cart 本身上调用。
    【解决方案2】:

    假设您正在使用 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
    

    【讨论】:

      【解决方案3】:

      在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
      

      希望对你有所帮助。

      【讨论】:

        【解决方案4】:

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

        @cart.line_items
        

        【讨论】:

        • 如何访问嵌套属性我知道,但我不知道如何在我的功能测试中模拟带有嵌套属性的发布请求。
        猜你喜欢
        • 1970-01-01
        • 2011-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多