[rspec-users] Using and_yield to pass multiple or no iterations

Doug Livesey lists at ruby-forum.com
Thu Jun 5 05:46:54 EDT 2008

Hi, imagine there's a class called Egg which has the following method
(which calls another method):

def do_thing
  has_iterated = false

  self.each_row do |row|
    has_iterated = true unless has_iterated


Stupid code, I know.
I have two questions with it. The first is, would it be possible to set
it up to test the case when each_row operates on an empty Array? Sort of
like this:

it "should return false if it does not iterate over anything" do
  @egg.stub!( each_row ).and_yield( nil ) # I know this doesn't work
  @egg.do_thing.should be_false

it "should return true if it does iterate over something" do
  @egg.stub!( each_row ).and_yield( :value )
  @egg.do_thing.should be_true

Secondly, is this the best (correct) way to pass multiple values to
iterate over?

it "should be doing something else, too"
  @egg.stub!( :each_row ).
    and_yield( :first_value ).
    and_yield( :second_value ).
    and_yield( :third_value )
  @egg.do_thing.should be_true

As you can see, my understanding of and_yield() is *very* imperfect, so
any & all pointers are very gratefully received.
Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list