[rspec-users] Stubbing Enumerable#each

Pat Maddox pergesu at gmail.com
Mon Aug 6 02:16:53 EDT 2007


On 8/5/07, Scott Taylor <mailing_lists at railsnewbie.com> wrote:
>
> I have a mock of an instance of a class which descends from Array:
>
> class ArrayDescendent < Array; end
>
> #... in the specs...
> @descendent = mock ArrayDescendent
>
> How would I stub out ArrayDescendent#each, which is inherited from
> Array, to return multiple values successively?  I could use
> and_yield, but that is raising an arity error (the anonymous function/
> block should expect only *one value at a time, but and_yield is
> yielding both values once).  Should I be using a lambda expression here?
>
> Tips are welcome...Thanks,
>
> Scott
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>

Hey Scott,

I'm not sure if there's a way you can currently do that (there may be
and I just couldn't figure it out).  However I agree it's useful, and
I whipped up a quick patch to provide that behavior.
http://rubyforge.org/tracker/index.php?func=detail&aid=12841&group_id=797&atid=3151

My example spec is

      it "should support yielding consecutive values" do
        yielded_values = []
        @obj.stub!(:method_that_yields).and_yield_consecutively("abc",
123, :foobar)
        @obj.method_that_yields {|val| yielded_values << val }
        yielded_values.should == [ "abc", 123, :foobar ]
        @obj.rspec_verify
      end


How's that?

Pat


More information about the rspec-users mailing list