How can I stub find_each for rspec testing in rails 3

Aaron picture Aaron · Dec 8, 2010 · Viewed 9.2k times · Source

I was wondering how to test a find_each call in rspec. I'm used to simply stubbing what I want my models to return so I don't rely on test data in the db like this:

MyClass.stub(:find).and_return(my_mock)

However, in another class I'm doing this:

MyClass.find_each do |instance_of_my_class|
  do_stuff_here_on(instance_of_my_class)
end

I find that if I do this:

MyClass.stub(:find_each).and_return([one_mock, two_mock])

in the spec test, the "do stuff here" part is not being executed. Does anyone know how to stub a find_each for rspec testing?

Answer

Iain picture Iain · Dec 8, 2010

You can use and_yield to make rspec call the block passed to the mock:

MyClass.stub(:find_each).and_yield(one_mock).and_yield(two_mock)