ruby-on-railsunit-testing

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?


Solution

  • 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 }