How to test factory pattern using Mocha in Ruby?

I'm having trouble getting this simple mocha test to work

Diclaimer I'm new to mocha!

My Factoryclass

# lib/fabtory.rb
class Factory
  def self.build klass, *args
    klass.new *args
  end
end

My test code

# test/test_factory.rb
class FactoryTest < MiniTest::Unit::TestCase

  # my fake class
  class Fake
    def initialize *args
    end
  end

  def test_build_passes_arguments_to_constructor
    obj = Factory.build Fake, 1, 2, 3
    obj.expects(:initialize).with(1, 2, 3).once
  end

end

Output

unsatisfied expectations:
- expected exactly once, not yet invoked: #<Fake:0x7f98d5534740>.initialize(1, 2, 3)
+1
source share
1 answer

A method expectssearches for method calls after it is called.

You need to change the settings a bit:

def test_build_passes_arguments_to_constructor
  fake = mock()
  Fake.expects(:new).with(1, 2, 3).returns(fake)
  assert_equal fake, Factory.build(Fake, 1, 2, 3)
end
+2
source

Source: https://habr.com/ru/post/1696958/


All Articles