[rspec-users] Can't use #exactly when #and_return influences it.

David Chelimsky dchelimsky at gmail.com
Thu Nov 1 06:54:58 EDT 2007


On Nov 1, 2007 5:26 AM, pangel <pangel.neu at gmail.com> wrote:
>
> I want my class Reader to loop on the content of its Stack until false is
> returned. I also want an optional argument to exist that limits how many
> times the stack will be read, even if some elements are left. I was trying
> to spec this last bit but ended up on a false positive.
>
>
> Hope the example will be clear enough:
>
> #spec_reader.rb
> describe Reader do
>  it "should stop reading items when called with a limit" do
>   @stack = mock(Stack)
>   Stack.should_receive(:new).and_return(@stack)
>
> @stack.should_receive(:read).exactly(3).times.and_return(2,4,1,5,3,1,false)

This should probably not be allowed.

>
>   @reader = Reader.new
>   @reader.read_stack(3)
>  end
> end
>
> # reader.rb
> class Reader
>  def initialize
>   @stack = Stack.new
>  end
>
>  def read_stack(limit = 0) #0 = read until false is returned
>   while val = @stack.read
>    # Not implemented on purpose!
>    # return if limit == 0
>    # limit -= limit
>    ...
>   end
> end
>
> So the test should fail, because the use of the limit argument has not been
> implemented yet and #read gets called 7 times. But the test actually passes.
> I looked into it a bit and it seems that number of arguments in #and_return
> overrides the arguments of #exactly.
>
> Did I misunderstand the point of #exactly or should I build my code
> differently so that the value returned by #and_return does not influence how
> many times #read is called?

I think this is a bug, but the question is - what is the bug? I think
the mock should complain when you set exactly(n).times and then give
it a different number of return values.

WDYT?


More information about the rspec-users mailing list