[rspec-users] 2nd attempt at mocking and stubbing

Nick Hoffman nick at deadorange.com
Fri Sep 5 17:44:20 EDT 2008

So, after reading all of those fantastic emails discussing testing  
behaviour vs state, I decided to try mocking and stubbing a couple of  
methods. I think I did well on my first one, but I'm not sure what the  
best way to spec the following method is:

1     class RentalMap
166   def add_properties
167     Property.find(:all, :conditions => 'latitude NOT NULL AND  
longitude NOT NULL').each do |p|
168       add_marker p.address, p.latitude, p.longitude,  
169     end
170   end

In my spec, I figured I would:
-Create a RentalMap object.
-Mock two properties.
-Setup expectations on the two mock properties.
-Stub the call to Property#find .
-Stub the call to RentalMap#add_marker .
-Stub the call to RentalMap#generate_marker_contents .

Here's what I wrote:

185   describe '#add_properties' do
186     it 'should add properties to the map' do
187       map             = RentalMap.new @map_name, @latitude,  
188       mock_property1  = mock 'property'
189       mock_property2  = mock 'property'
191       Property.stub!(:find).and_return mock_property1,  
192       map.stub!(:add_marker).and_return '?'
194       mock_property1.should_receive(:address  ).and_return '400  
Bloor Street'
195       mock_property1.should_receive(:latitude ).and_return 12.34
196       mock_property1.should_receive(:longitude).and_return 56.78
197       mock_property2.should_receive(:address  ).and_return '500  
Bloor Street'
198       mock_property2.should_receive(:latitude ).and_return 12.45
199       mock_property2.should_receive(:longitude).and_return 56.89
200       map.stub!(:generate_marker_contents).twice.and_return 'Some  
contents for the first property', 'Some contents for the second  
202       map.should_receive(:add_marker).with mock_property1.address,  
mock_property1.latitude, mock_property1.longitude,  
203       map.should_receive(:add_marker).with mock_property2.address,  
mock_property2.latitude, mock_property2.longitude,  
205       map.add_properties
206     end
207   end

However, this fails with:

Spec::Mocks::MockExpectationError in 'RentalMap#add_properties should  
add properties to the map'
Mock 'property' received unexpected message :each with (no args)

I don't think that I should be stubbing Array#each , but I'm not sure  
what I should change. Any suggestions?


More information about the rspec-users mailing list