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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With