[rspec-users] #stub! and #should_receive on the same method

Nick Hoffman nick at deadorange.com
Thu Sep 25 13:47:33 EDT 2008


I'm calling #stub! and #should_receive on the same method within a  
class, and am finding that the method doesn't return the value given  
to #stub!

216     it 'should make a map marker' do
217       mock_property = mock 'property',
218         :address => '400 Bloor Street',
219         :title => 'Some Title',
220         :latitude => 12.34,
221         :longitude => 56.78,
222         :is_a? => true
223       mock_marker   = mock 'gmarker'
224
225       RentalMap.stub!(:generate_marker_contents).and_return 'Some  
content'
226       GMarker.stub!(:new).and_return mock_marker
227       GMarker.should_receive(:new).with \
228         [mock_property.latitude, mock_property.longitude],
229         {:title => mock_property.title, :info_window =>  
RentalMap.generate_marker_contents(mock_property)}
230
231       marker = RentalMap.make_marker(mock_property)
232       puts "marker is a [#{marker.class}]"
233       marker.should equal(mock_marker)
234     end

I want to stub GMarker#new to return the mock GMarker on line 223. I  
also want to ensure that GMarker#new is being called once with certain  
arguments, as seen on lines 227-229.

However, this spec fails, and the 'gmarker' variable is nil:
gmarker is a [NilClass]
F.
1)
NoMethodError in 'RentalMap#make_marker should make a map marker'
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.a?
./spec/models/rental_map_spec.rb:233:

If I comment out lines 227-229, the spec succeeds, and the 'marker'  
variable is the expected mock object:
marker = [Spec::Mocks::Mock]

With lines 227-229 uncommented, why is the 'gmarker' variable nil?

Thanks!
Nick


More information about the rspec-users mailing list