views:

104

answers:

1

I am trying to Mock an object that is being passed into another object, and am having no success. Can someone show me what I am doing wrong?

class Fetcher
  def download
    return 3
  end
end

class Reports
  def initialize(fetcher)
    @fetcher = fetcher
  end
  def status
    @fetcher.download
  end
end


describe Reports do
  before(:each) do
  end

  it "should get get status of 6" do
    Fetcher.should_receive(:download).and_return(6)
    f = Reports.new(Fetcher.new)
    f.status.should == 6
  end
end

The spec still reports status returning 3, not my intended 6.

Certainly I am missing something here. Any thoughts?

+1  A: 

In the test, what I think you're trying to do is this (I think)

it '...' do
  some_fetcher = Fetcher.new
  some_fetcher.should_receive(:download).and_return(6)

  f = Reports.new(some_fetcher) 
  f.status.should == 6
end

when you say Fetcher.should_receive(:download), you're saying the CLASS should receive the call 'download', instead of INSTANCES of the class...

Hope this helps! If it's not clear, just let me know!

btelles
Thanks, that was it. HOWEVER....two things.1. Why don't instances of Fetcher inherit changes to the class? If I added a new method to Fetcher and then instantiated it, it would have that method, wouldn't it?2. I arrived at the above code from a Peepcode screencast on rspec. The original code was for a Rails model, and looked like this: def mock_feed(zipcode, how_many=1) xml = ... Weather.should_receive(:open).exactly(how_many).times. with("http://weather.yahooapis.com/forecastrss?p=#{zipcode}"). and_return(xml) endWhy does his class modification work, and not mine?
For #1, you could do that, but problems easily come up where you're not guaranteed to have the second class instantiated at the right time. Instead of defining new methods the way you described, you may want to try using 'instance_eval'.So if you wanted to add a method to Fletcher, you could do : Fletcher.class_eval do def some_method ... end endSome other guys explain this better than I can. Here are some links:http://bmorearty.wordpress.com/2009/01/09/fun-with-rubys-instance_eval-and-class_eval/#2, I couldn't quite make out problem. Could you try again?
btelles