Pt-E-2
Activity Description
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.
Author’s Solutions
blah
Readers’ Solutions
Long says
My attempt:
In test/unit/cart_test.rb:
def new_cart_with_one_product(product_name)
cart = Cart.create
cart.add_product(products(product_name).id)
cart
end
test 'cart should create a new line item when adding a new product' do
cart = new_cart_with_one_product(:one)
assert_equal 1, cart.line_items.count
# Add a new product
cart.add_product(products(:ruby).id)
assert_equal 2, cart.line_items.count
end
test 'cart should update an existing line item when adding an existing product' do
cart = new_cart_with_one_product(:one)
# Re-add the same product
cart.add_product(products(:one).id)
assert_equal 1, cart.line_items.count
end
h4. Arun says
I am doubtful whether the question was about creating a new and duplicate line items or products.
I thought the answer is along the lines of
test "unique_product_should_be_saved"
product = Product.new(:title => "unique-title",
:description => "a unique product",
:image_url => "unique.png",
:price => 22)
assert product.save
end
test "non_unique_product_should_error_out"
product = Product.new(:title => "unique-title",
:description => "a unique product",
:image_url => "unique.png",
:price => 22)
assert !product.save
assert_equal "has not been saved since it is a duplicate ", product.errors[:title].join('; ')
end
Doc says
File: test/unit/cart_test.rb
require 'test_helper'
class CartTest < ActiveSupport::TestCase
test "cart line item should save price" do
cart = carts(:cart1)
[:ruby, :loremipsum, :ruby].each do |which_product|
product = products(which_product)
item = cart.add_product product.id
assert_equal item.price, product.price,
"cart line item did not save price"
end
end
test "cart line item quantity should increment" do
cart = carts(:cart2)
product = products(:ruby)
multiple = 3
multiple.times { cart.add_product product.id }
item = cart.line_items.find_by_product_id product.id
assert_equal multiple, item.quantity,
"cart line item quantity is incorrect"
end
test "cart line item price should equal most-recent price" do
cart = carts(:cart3)
product = products(:ruby)
sale_price = 0.8 * product.price
[product.price, sale_price, 100].each do |price|
cart.add_product product.id, price
item = cart.line_items.find_by_product_id product.id
assert_equal price, item.price,
"price #{item.price} is incorrect; should be #{price}"
end
end
test "cart should be destroyed" do
cart = Cart.create
assert cart.save, "unable to create cart"
cart.destroy
begin
cart = Cart.find(cart.id)
rescue ActiveRecord::RecordNotFound
cart = nil
end
assert_nil cart, "cart has not been destroyed"
end
end
File: test/fixtures/carts.yml
...
cart1: {}
cart2: {}
cart3: {}

