How to test factory pattern using Mocha in Ruby?

為{幸葍}努か 提交于 2019-12-24 13:16:15

问题


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

Diclaimer I'm new to mocha!

My Factory class

# 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:


The expects method look for method calls after his call.

You have to setup things a little bit different:

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


来源:https://stackoverflow.com/questions/17204371/how-to-test-factory-pattern-using-mocha-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!