Search code examples
ruby-on-railsmocha.jsstub

Can I add custom side-effects to a stub in Rails Mocha?


My team uses the Mocha gem for stubbing in Rails. I understand how to stub a method with stubs such that it does nothing, or returns a specific value, but is there a way to stub it such that it runs a certain line of code when called?

I'm looking for something like this:

object.stubs(:method).runs(p 'Hello world!')

Does this exist? I'm open to using additional gems, or implementing whatever methodology people come up with.


Solution

  • It appears that .with() takes a block, so you can use logic to validate the arguments to a method. Here's its source with comment:

    #   object = mock()
    #   object.expects(:expected_method).with() { |value| value % 4 == 0 }
    #   object.expected_method(17)
    #   # => verify fails
    def with(*expected_parameters, &matching_block)
      @parameters_matcher = ParametersMatcher.new(expected_parameters, &matching_block)
      self
    end
    

    Mocha probably won't mind if you call side_effect(); true in there instead of validate a parameter.