Rhs
Rhs

Reputation: 3318

Ruby On Rails Mocha Expects

I have a function which I'm trying to test

@@described_class.expects(:foo).with(
  1,
  2,
  <any number>
)

@@described_class.bar()

so here my function bar calls foo. Is there a way to set this up where :foo's third parameter can be any number?

Upvotes: 1

Views: 3049

Answers (2)

Tim Krins
Tim Krins

Reputation: 3819

If you want to ensure it is an Integer, you can use

@@described_class.expects(:foo).with(1, 2, is_a(Integer))

If you only really care about the first two parameters being 1 and 2, you could use anything for the last argument.

@@described_class.expects(:foo).with(1, 2, anything)

You can read the docs for parameter matchers specifically at https://mocha.jamesmead.org/Mocha/ParameterMatchers.html

Upvotes: 1

mokagio
mokagio

Reputation: 17461

From the question title and the code snipped I'm assuming you're using this version of mocha.

If that's the case then you can pass a block to your with and define your expectations in there, see the docs here.

object = mock()
object.expects(:expected_method).with() { |value| value % 4 == 0 }
object.expected_method(16)
# => verify succeeds

object = mock()
object.expects(:expected_method).with() { |value| value % 4 == 0 }
object.expected_method(17)
# => verify fails

The documentation doesn't have an example with more than one parameter as input, but given Ruby's nature I'd assume something like this would work

@@described_class.expects(:foo).with { |first, second, third| first == 1 && second == 2 }

Upvotes: 2

Related Questions