DEV Community

Caleb Hearth
Caleb Hearth

Posted on • Originally published at calebhearth.com on

Avoid Test Delays And Speed Up Your Development Cycle by Mocking Callbacks

Mocking is one way to achieve isolation in tests. It is the practice of using a fake object in place of a collaborator object. In the simplest case, a mock will accept a method call, do nothing, and return a value (usually nil in Ruby). Mocks can also stub methods to return realistic values. They can provide static responses or use arguments to calculate a return value. It’s often as simple as specifying the expected method arguments and a response.

A simple stubbing might look like this:

stubs { mailer.deliver("a message") }.with { "canned response" } mailer.deliver("a message") # => "canned response" 
Enter fullscreen mode Exit fullscreen mode

But stubbing methods isn’t always so straightforward. When a Ruby method takes a block to call later, it’s harder to identify whether, when, and how to call that block. It’s not as easy as the method mock above that can discard or do minimal work with arguments. Blocks often have side effects that may be important and that we need to assert against.

When a Ruby method takes a...

http://calebhearth.com/a/mocking-callbacks

Top comments (0)