2011-07-05 28 views
0

我正在编写我的第一个Rails'Store'应用程序,并且在我的一个测试中遇到了一些奇怪的事情。我想测试add_product方法上cart.rb:在Rails中更新ActiveRecord测试

class Cart < ActiveRecord::Base 
    has_many :line_items, :dependent => :destroy 

    def add_product(product) 
    current_item = line_items.find_by_product_id(product.id) 
    if current_item 
     current_item.quantity += 1 
    else 
     current_item = line_items.build(:product_id => product.id, :price => product.price)  
    end 
    current_item 
    end 

    def total_price 
    line_items.to_a.sum { |item| item.total_price } 
    end 

end 

我测试,加入同样的产品到购物车两倍的数量增加,而不是增加一个新行(LINE_ITEM)。这是测试:

test "line item quantity is increased when duplicate product is added" do 
    cart = carts(:one) 
    ruby_book = products(:ruby) 

    cart.add_product(ruby_book) 
    cart.save  
    assert_equal 1, cart.line_items(ruby_book).to_a.count 

    cart.add_product(ruby_book) 
    cart.save 
    assert_equal 1, cart.line_items(ruby_book).to_a.count 
    assert_equal 2, cart.line_items(ruby_book).first.quantity # fail! 
    end 

我在最后断言失败。数量是1,我期望2。我已经检查了test.log文件,没有更新曾经运行过我的sqlite3实例...如果需要,我可以添加日志或Fixtures文件,但我确定这是这是一个新手问题,它不会被要求!

由于提前,

斯图

+1

'cart.line_items(ruby_book)'是不正确的。我想你可能需要'cart.line_items.find_all_by_product_id(ruby_book.id)'。这不是针对解决你的问题。此外,它看起来像你可以分解你的一个测试到2或3个单独的测试。 –

+0

感谢@Wizard of Ogz 你是对的,那里有太多的断言。我确信cart.line_items(ruby_book)会生成与替代方案相同的SQL ...但我也会检查它。 – Stu

+0

我检查了你的建议,并且它是Ogz的@Wizard点 - 非常感谢。 对于以下这个人,我行生成的SQL没有限制到的product_id都: SELECT “line_items” * FROM “line_items” WHERE( “line_items” .cart_id = 980190962) 的唯一原因,工作,它没有其他用户也有一个购物车! – Stu

回答

1

要修改的订单项的数量属性,但不保存更改。 调用父级保存不会保存子级的属性。 您可以在增量行之后的add_product方法中调用save current_item。

if current_item 
    current_item.quantity += 1 
    current_item.save 
else 
+0

嗨@simianarmy 谢谢 - 工作。 虽然解决方案让我感到困扰。看起来奇怪的是,我现在必须在第一次添加产品时明确地调用.save,但我不必在添加现有产品时调用它,因为它在add_product的“else”子句中调用方法。 有没有更好的方法来做到这一点?我现在可能总是知道产品是否已经存在或不存在... 干杯,Stu – Stu

+0

啊 - 我刚刚读了你的答案。这是我打电话保存的** line_items **集合。 再次欢呼 – Stu

相关问题