Interacting directly with brains is not easy, so I have a little Gateway Pattern in use with some Dependency Inversion.
NumberCruncher
is a wrapper for my Brain
class.
class NumberCruncher
def initialize brain = Brain.new
@brain = brain
end
def times_one_hundred *numbers
numbers.map &@brain.method(:multiply_by_100)
end
end
I'm getting an error when testing though:
NameError: undefined method `multiply_by_100' for class `Mocha::Mock'
Here's the test
class NumberCruncherTest
def setup
@brain = mock
@cruncher = NumberCruncher.new @brain
end
def test_times_one_hundred
@brain.expects(:multiply_by_100).with(1).returns(100)
@brain.expects(:multiply_by_100).with(2).returns(200)
@brain.expects(:multiply_by_100).with(3).returns(300)
assert_equal [100, 200, 300], @cruncher.times_one_hundred(1,2,3)
end
end
I'm assuming it's because of the &@brain.method(:multiply_by_100)
call and mocha works by using method_missing
or something. The only solution seems to be to change the setup
class NumberCruncherTest
class FakeBrain
def multiply_by_100; end
end
def setup
@brain = FakeBrain.new
@cruncher = NumberCruncher.new @brain
end
# ...
end
However, I think this solution kind of sucks. It gets messy fast and it putting tons of Fake*
classes all over my tests. Is there any better way to do this with mocha?