small medium large xlarge

Generic-user-small
06 Jul 2015, 20:48
Seth Lytton (2 posts)

I have been trying to get the playtime code to work. I have added the delete buttons to each line item in the cart. I have also added a before filter to the carts controller that redirects the user to the store_path when the last line item in the cart has been deleted. This way users aren’t faced with an empty cart.

if @cart.line_items.length < 1
  redirect_to store_path, notice: 'Cart successfully emptied'
end

The issue arrises when I run this test:

  test "should show cart if there are items in it." do
    @cart.add_product(products(:ruby).id)
    session[:cart_id] = @cart.id
    get :show, id: @cart
    assert_response :success
  end

When I inspect the value of @cart.line_items.first using debugger, I see the following:

#<LineItem id: nil, product_id: 207281424, cart_id: 980190962, created_at: nil, updated_at: nil, quantity: 1, price: #<BigDecimal:7fb291758a78,'0.495E2',18(27)>>

Then I inspect the value of @cart.line_items in the before filter in the controller and I get:

#<ActiveRecord::Associations::CollectionProxy []>

Ultimately the test fails with: Expected response to be a <success>, but was <302>. This make sense because apparently after control passes to the cart controller, the line_item that was created has been lost or destroyed…

When I remove the before filter, everything works as expected.

Clearly there is some difference between dev and test in the way that data is handled, but I haven’t been able to find anything that will solve this problem.

Any insight would be much appreciated.

Generic-user-small
06 Jul 2015, 22:29
Seth Lytton (2 posts)

I finally figured this out.

In order to persist the added product in the @cart instance variable I needed to add an explicit call to save.

 test "should show cart if there are items in it." do
    @cart.add_product(products(:ruby).id)
    session[:cart_id] = @cart.id
    **@cart.save!**
    get :show, id: @cart
    assert_response :success
  end
You must be logged in to comment