[rspec-users] Testing with has_many associations

Chris Parsons chris at edendevelopment.co.uk
Wed Apr 9 05:30:17 EDT 2008


On 9 Apr 2008, at 06:25, Andy Croll wrote:

>   current = self.items.find_by_name(product.name)


You're finding by the CartItem name and passing the product name - it  
looks like that's drawing a blank match when you're expecting it not to.

How about a cart_item_spec.rb:

describe CartItem do
   it "should be created successfully from a new product" do
     CartItem.new_from_product(mock_model(Product, :name => "name" ))
     CartItem.find_by_name("name").should_not be_nil
   end
end

I'm guessing this spec will fail with your current code as I don't  
think CartItem::new_from_product is working.

I'd also probably break down the specs differently and wrap the call  
to items and make the specs more contained:

class Cart
   def self.find_items_by_name(name)
	items.find_by_name(name)
   end
end

...and mock this method when testing add_product:

it "should add the product when it doesn't already exist in the cart" do
   @cart.should_receive(:find_items_by_name).with("name").and  
return(nil)
   @cart.add_product(@product)
   @cart.items.should have(1).item
end

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

HTH,
Chris




More information about the rspec-users mailing list