0

I need to mock an object whose class is expected to have a few constants defined, e.g:

class Driver
  DRIVER_NAME = "google"
end

I don't want to simply use instances of the class in my unit tests because of expensive initialization, plus it has a simple interface so it's optimal to mock. If I could simply subclass Mocha::Mock and add a few constants that would be perfect. I haven't found a way to instantiate those subclasses though. They require "mockery" as the initialize argument. I tried:

TestDriver.new(self.mock.instance_method_get(:@mockery))

Which quite funnily resulted in:

unexpected invocation: #<Mock:0x35c0690>.instance_method_get(:@mockery)

The source of Mocha is quite complex and entangled. I can't even find the point where mock is created for each Minitest::Test object.

So how do I subclass mocks in Mocha? Is there a straight forward way?


My backup solution is to simply use the three-line class shown above with driver.stubs(:name)... instead of using mocks, but that feels like the wrong way to solve the issue.

Vega
  • 27,856
  • 27
  • 95
  • 103
Hubro
  • 56,214
  • 69
  • 228
  • 381

1 Answers1

0

I just realized (by accident) that I can call expects on any object, not just mocks...

class TestDriverManager
  def test_something
    foo = TestDriver.new
    foo.expects(:valid?).returns(true).once

    # ...
  end

  class TestDriver
    DRIVER_NAME = "test"
    ...
  end
end

So there really is no need, at least not in my case, to subclass mock.

Hubro
  • 56,214
  • 69
  • 228
  • 381