How to Use: Minitest Mocks

Prerequisite

Usage

# Create a mock
mock = Minitest::Mock.new

# Add expectations.
#
# Arguments:
#   1. Method name
#   2. What to return when called
#   3. Expected inputs
mock.expect(:read!, { result: 1 }, ['first'])

# Now you pass the mock around and execute your tests.
subject = described_class.new(something: mock)
subject.add(:a)

# Verify the expectations were met.
mock.verify

Limitations

You can’t mock #respond_to? for some reason, at least I could not when I tried it. But it might have been a bug and it works now? Can somebody verify?

Why is this important? You might want to pass a mock to a validator like this one:

def validate_set!(state)
  unless state.respond_to?(:[]=)
    raise(ArgumentError, 'Given state object does not respond to `:[]=`')
  end

  arity = state.method(:[]=).arity
  unless arity == 2
    raise(
      ArgumentError,
      "Given state object's `:[]=` method arity must be 2, got: #{arity}"
    )
  end
end

Reference

Further reading: