08 Nov 2013, 19:56

Colin Williams (9 posts)

I’m having trouble with the line items count for addding duplicate products. I’m including my cart and cart_test code below…

::This is the hint from the wiki: :

Add unit tests which add unique products and duplicate products. Note that you will need to modify the fixture to refer to products and carts by name, for example product: ruby.

Hint: add two tests to test/models/cart_test.rb; in one test create a cart, add two different books to the cart, and then make assertions as to what the cart.line_items.size and cart.total_price should be. Make sure to save the LineItems that you create before making these assertions.

test "test adding duplicate products" do
  product4 = Product.create(title:"same_title", description:"this is the same book", image_url: "same.jpg",price: "23.23")
  cart = Cart.new
  cart.add_product(product4) #.save
  cart.add_product(product4) #.save
  puts cart.inspect
  puts "line_items"
  puts cart.line_items.inspect
  assert cart.save
  assert cart.line_items.size == 1
  assert  cart.line_items[0].quantity == 2 

class Cart < ActiveRecord::Base has_many :line_items, dependent: :destroy
def add_product(product)
  current_item = line_items.find_by(product_id: product.id) #.first
  if current_item current_item.quantity += 1
    current_item = line_items.build(product_id: product.id,price: product.price)
def total_price
  line_items.to_a.sum { |item| item.total_price }

#<ActiveRecord::Associations::CollectionProxy [#<LineItem id: 980190963, product_id: 980190963, cart_id: nil, created_at: "2013-11-08 19:57:18", updated_at: "2013-11-08 19:57:18", quantity: 1, price: #<BigDecimal:340cfb0,'0.2323E2',18(18)>>, #<LineItem id: 980190964, product_id: 980190963, cart_id: nil, created_at: "2013-11-08 19:57:18", updated_at: "2013-11-08 19:57:18", quantity: 1, price: #<BigDecimal:340cfb0,'0.2323E2',18(18)>>]> F#<Cart id: nil, created_at: nil, updated_at: nil> ....E....EEEEE.......EEEE..

Finished tests in 1.004417s, 30.8637 tests/s, 63.7186 assertions/s.

1) Failure:
CartTest#test_test_adding_duplicate_products   [/home/discord/code/ruby/rails/depot/test/models/cart_test.rb:57]:
Failed assertion, no message given.
08 Nov 2013, 20:07

Colin Williams (9 posts)

As you can see from the printed line items, I have two line items for the same with the same product id, but different line item ids. From the logic of my add_product(product) method in the cart, I expect only one product to be created.

  You must be logged in to comment