Why are my unit tests failing?
Howdy, I'm having a bit of a problem getting my unit tests to pass. Specifically, the ones in *cart_test.rb* are failing.
test "add two different items" do
cart = Cart.create
book_one = products(:one)
book_two = products(:two)
cart.add_product(book_one.id).save!
cart.add_product(book_two.id).save!
assert_equal 2, cart.line_items.size
assert_equal book_one.price + book_two.price, cart.total_price
end
test "add two uni开发者_运维百科que items" do
cart = Cart.create
ruby_book = products(:ruby)
cart.add_product(ruby_book.id).save!
cart.add_product(ruby_book.id).save!
assert_equal 2*ruby_book.price, cart.total_price
assert_equal 1, cart.line_items.size
assert_equal 2, cart.line_items[0].quantity
end
Here's my repository: https://github.com/zackster/Agile-Web-Development-w--Rails----DEPOT-application
Could somebody please help me understand what's going on? I believe the tests are failing because the items aren't actually being added to the cart, but it could be something else entirely [I'm a rails novice ]. . . thanks!
The CartTest tests are failing because in Cart::add_product, you aren't actually tying a new line_item to a cart -- just creating orphaned line_items with a raw LineItem.create
. To tie to a cart, you can change the line that was creating a LineItem with no relationship to the cart:
current_item = LineItem.new(:product_id => product_id, :price => product_price)
to actually create a new line item in the current cart's line_items collection:
current_item = line_items.create(:product_id => product_id, :price => product_price)
There were some other failures that you didn't specifically ask about, but I looked into them anyways...
Your products.yml does not specify an id field, so the product_id of 1 in line_items.yml does not end up referencing any product when you run the fixtures. You can hard-code id: 1
, etc in your products.yml to address this.
Next, there is just a typo in the CartsControllerTest -- @cart_id
isn't defined, and should instead be @cart.id
Finally, that unveils one other problem, which is actually a logic problem. Now your test to destroy a product fails, but this is actually because your logic does not allow you to destroy a product that has line_items (which your product does once we fixed the products.yml file to have ids specified). So... really the test is wrong and the code is right there, I suppose.
精彩评论