Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

How can I stub find_each for rspec testing in rails 3

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?

question from:https://stackoverflow.com/questions/4382685/how-can-i-stub-find-each-for-rspec-testing-in-rails-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...