[rspec-users] Testing with has_many associations

Andy Croll lists at ruby-forum.com
Wed Apr 9 01:25:00 EDT 2008


Hi I'm trying to be good and practice full BDD on my current project,
and don't want to abandon it as I have previously (expediency triumphed
unfortunately). So expect me to be making frequent 'noob' style posts...

My current issue is with testing assignation across a has_many
relationship. I'm aware I shouldn't be testing the functionality of
Rails, but this is behaviour of my code.

cart_spec.rb:

describe Cart do
  before(:each) do
    @product = mock "Trousers"
    @product.stub!(:class).and_return("Product")
    @product.stub!(:name).and_return("Brown Trousers")
    @product.stub!(:price).and_return(23.99)
    @cart = Cart.new
  end

  it "should have 1 item after adding a Product" do
    @cart.add_product(@product)
    @cart.items.should have(1).item
  end

  it "should have 1 item but with quantity 2 after adding the same
product twice" do
    @cart.add_product(@product)
    @cart.add_product(@product)
    @cart.items.should have(1).item
  end
end

cart.rb:

class Cart < ActiveRecord::Base

  has_many :items, :class_name => "CartItem", :dependent => :destroy

  def add_product(product)
    current = self.items.find_by_name(product.name)
    if current
      current.increment_quantity
    else
      self.items << CartItem.new_from_product(product)
    end
  end

end

fails with:

'Cart should have 1 item but with quantity 2 after adding the same
product twice' FAILED expected 1 item, got 2

*****

Can anyone explain to me what I'm missing?
-- 
Posted via http://www.ruby-forum.com/.


More information about the rspec-users mailing list