Ruby Mocha - how to specify ".with" multiple ".times"

2.4k views Asked by At

I would like to be able to chain multiple .with expectations together. At present I am putting them on separate lines -

foo.expects( :bar ).with( a )
foo.expects( :bar ).with( b )
foo.expects( :bar ).with( c )

With .returns you can just do -

foo.expects( :bar ).returns( a, b, c )

I would ideally like to be able to -

foo.expects( :bar ).returns( a, b, c ).with( a, b, c )

or

foo.expects( :bar ).returns( a, b, c ).with( a ).with( b ).with( c )
1

There are 1 answers

0
m26a On

You can't call with multiple times in the same expectation because with will override the previous one.

# File 'lib/mocha/expectation.rb', line 221

def with(*expected_parameters, &matching_block)
  @parameters_matcher = ParametersMatcher.new(expected_parameters, &matching_block)
  self
end

It's different with returns because returns accumulate the expectations.

# File 'lib/mocha/expectation.rb', line 373

def returns(*values)
  @return_values += ReturnValues.build(*values)
  self
end

So, yes, you have to do it in the way you're doing, calling expects multiple times in the same object.

foo.expects(:bar).with(a)
foo.expects(:bar).with(b)
foo.expects(:bar).with(c)