更新的ActiveRecord在Rails的测试 [英] Updating ActiveRecord in Rails test
问题描述
我在写我的第一个Rails的商店的应用程序,我穿过一些奇怪的未来在我的测试之一。我试图测试上cart.rb的add_product方式:
类车<的ActiveRecord :: Base的
的has_many:line_items,:依赖=> :破坏
高清add_product(产品)
current_item = line_items.find_by_product_id(product.id)
如果current_item
current_item.quantity + = 1
其他
current_item = line_items.build(:PRODUCT_ID => product.id,:价格=> product.price)
结束
current_item
结束
高清TOTAL_PRICE
line_items.to_a.sum {|项目| item.total_price}
结束
结束
我测试,加入同样的产品到购物车两倍的数量增加了,而不是增加一个新行(line_item)。下面是测试:
做测试时,重复的产品添加行项目数量增加
购物车=车(为1)
ruby_book =产品(:红宝石)
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#失败!
结束
我得到一个失败的最后断言。该数量是1,我在那里想到2.我已经检查了test.log中文件并没有更新过对我的sqlite3的实例上运行...我可以根据需要添加日志或灯具的文件,但我敢肯定,这是这样的新手问题,它不会被要求<!/ P>
在此先感谢,
斯图
您正在修改的行项目的数量属性,但不能保存更改。 调用保存父救不了孩子们的属性。 您可以拨打节省current_item的增量线后add_product方法。
如果current_item
current_item.quantity + = 1
current_item.save
其他
I'm writing my first Rails 'Store' app and I'm coming across something weird in one of my tests. I'm trying to test the add_product method on cart.rb:
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
I'm testing that adding the same product to a cart twice increases the quantity rather than adding a new line (line_item). Here's the test:
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
I get a fail on the last assert. The quantity is 1, where I expect 2. I've checked the test.log file and no update is ever run against my sqlite3 instance... I can add the log or the Fixtures files if necessary, but I'm sure this is such a newbie question that it won't be required!
Thanks in advance,
Stu
You are modifying the line item's quantity attribute, but not saving the change. Calling save on the parent won't save the children's attributes. You can call save on current_item in the add_product method after the increment line.
if current_item
current_item.quantity += 1
current_item.save
else
这篇关于更新的ActiveRecord在Rails的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!