开发者

Updating ActiveRecord in Rails test

开发者 https://www.devze.com 2023-03-17 06:08 出处:网络
I\'m writing my first Rails \'Store\' app and I\'m coming across something weird in one of my tests. I\'m trying to test the add_product method on cart.rb:

I'm writing my first Rails 'Store' app and I'm coming across something weird in one of my tests. I'm trying to test the add_product method on cart.rb:

    class Cart < ActiveRecord::Base
  has_many :line_items, :dependent => :destroy

  def add_product(product)
    current_item = line_items.find_by_product_id(product.id)
    if current_item
      current_item.quantity += 1
    else
      current_item = line_items.build(:product_id => product.id, :price => product.price)      
    end
    current_item
  end

  def total_price 
    line_items.to_a.sum { |item| item.total_price }
  end

end

I'm testing that adding the same product to a cart twice increases the quantity rather than adding a new line (line_item). Here's the test:

test "line item quantity is increased when duplicate product is added" do
    cart = carts(:one)
    ruby_book = products(:ruby)

    cart.add_product(ruby_book)
    cart.save    
    assert_equal 1, cart.line_items(ruby_book).to_a.count

    c开发者_高级运维art.add_product(ruby_book)
    cart.save
    assert_equal 1, cart.line_items(ruby_book).to_a.count
    assert_equal 2, cart.line_items(ruby_book).first.quantity # fail!
  end

I get a fail on the last assert. The quantity is 1, where I expect 2. I've checked the test.log file and no update is ever run against my sqlite3 instance... I can add the log or the Fixtures files if necessary, but I'm sure this is such a newbie question that it won't be required!

Thanks in advance,

Stu


You are modifying the line item's quantity attribute, but not saving the change. Calling save on the parent won't save the children's attributes. You can call save on current_item in the add_product method after the increment line.

if current_item
  current_item.quantity += 1
  current_item.save
else
0

精彩评论

暂无评论...
验证码 换一张
取 消