Saturday, January 15, 2011

Rails - Iteration E1 - line_item aggregation starts new

Take 2 on smarter cart!

First: add a unit test for the cart.add_product method

test "cart aggregates line items" do
c = carts(:one)
assert_equal 0, c.line_items.count, "cart items not empty at start of test"
p = products(:ruby)
item = c.add_product(p.id)
assert_equal 1, c.line_items.count, "first product add did not create new line item"
assert_equal 1, item.quantity, "new item quantity not 1"
item = c.add_product(p.id) #hold reference for future testing
assert_equal 1, c.line_items.count, "readd product caused increase in line items count"
assert_equal products(:ruby).id, item.product.id, "a problem with product id between line item and orig"
end

(Note to self: originally tried to do above like:
- assert_difference('c.line_items.count') do
- p = products(:ruby)
- c.add_product(p.id)
- c.save
- end
Note that the assert_difference requires a DB save event. Decided I didn't like that extra dependency on a unit test. Also note that the assert_difference requires a string not an object expression.)

Second: modify line_item_controller test to show aggregation of line items

test "should create/update line_item" do
#original test when just creating new items (iteration D)
assert_difference('LineItem.count') do
post :create, :product_id => products(:ruby).id
end
assert_redirected_to cart_path(assigns(:line_item).cart)
#new test - just repeat old and this time no_difference
assert_no_difference('LineItem.count') do
post :create, :product_id => products(:ruby).id
end
assert_redirected_to cart_path(assigns(:line_item).cart)

now when I complete the line item tests everything (including listing of cart after add) works as intended.

No comments:

Post a Comment