[rspec-users] Testing with has_many associations

Andy Croll lists at ruby-forum.com
Wed Apr 9 07:22:32 EDT 2008


Chris Parsons wrote:

> it "should increment quantity when it does find a product" do
>    @cart.should_receive(:find_items_by_name).with("name").and
> return(@product)
>    @cart.add_product(@product)
>    @cart.items.should have(1).item
> end

My final solution for this was to write...

describe Cart do
  before(:each) do
    @product1 = mock_model Product, :name => "Brown Trousers", :price => 
23.99
    @product2 = mock_model Product, :name => "Yellow Shirt", :price => 
15.74
    @cart_item1 = mock_model CartItem, :name => "Brown Trousers", :price 
=> 23.99, :quantity => 1
    @cart = Cart.new
  end

  it "should increment quantity when it does find a product" do
    @cart_item1.should_receive(:increment_quantity).once.with(:no_args).and_return(2)
    @cart.should_receive(:find_item_by_name).twice.with("Brown 
Trousers").and_return(nil, @cart_item1)
    @cart.add_product(@product1)
    @cart.add_product(@product1)
    @cart.items.should have(1).item
  end
end

Which seems to work. I'm right?
-- 
Posted via http://www.ruby-forum.com/.


More information about the rspec-users mailing list