1

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)
Vega
  • 27,856
  • 27
  • 95
  • 103
Mulan
  • 129,518
  • 31
  • 228
  • 259

1 Answers1

2

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
Mulan
  • 129,518
  • 31
  • 228
  • 259
Thiago Lewin
  • 2,810
  • 14
  • 18
  • I made this change and we got a little further. But I'm still getting an error : – Mulan Jun 20 '13 at 02:34
  • Correct, why is Mocha not detecting that `initialize` was called? – Mulan Jun 20 '13 at 02:36
  • I made a small update to your answer that makes it a little more complete. Without chaining a `#returns` call, the constructor would actually return nil which makes it hard to do test anything returned from the factory method. – Mulan Jun 21 '13 at 19:22
  • @naomik please put notes in comments and allow the original poster to edit their answer accordingly – nowk Jun 21 '13 at 19:26
  • 1
    @kwon that kind of thing can be pretty hard to explain. Even in this seemingly simple case. The alternative is I post an answer to my own question and mark it as accepted because it is more complete. I wanted to give the credit to tlewin, but I also want people that visit this question to see the most complete answer. If he doesn't like my edits, he can always rollback. A big part of SO is empowering the user base and trusting them to do the right thing. I believe making the edit on the accepted answer without creating a long-winded discussion in the comments is the correct move here. – Mulan Jun 21 '13 at 19:34