Reputation: 154
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
Upvotes: 0
Views: 305
Reputation: 1507
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
Upvotes: 1