Karl San Gabriel
Karl San Gabriel

Reputation: 25

How does Mocha generate a mock out of MyRubyClass.new in ruby?

My background is Java and I am new to Ruby. I saw a mocking/stubbing framework called Mocka. I saw this example test method:

require 'test/unit'
require 'mocha/test_unit'

class MiscExampleTest < Test::Unit::TestCase
  # ...

  def test_mocking_an_instance_method_on_a_real_object
    product = Product.new
    product.expects(:save).returns(true)
    assert product.save
  end

  #...
end

What mechanism was used to "automatically" create a mock object of Person class (or object)? Not sure what to Google for.

If it was something like this

product = mock(Product.new)

I'd easily get it.

Thank You! :)

Upvotes: 0

Views: 216

Answers (1)

phoet
phoet

Reputation: 18845

in general, this is referred to as "monkey patching".

ruby has the concept of open classes, so at runtime you can mess around with it.

in the specific case of mocha, i assume that it is this piece of code here: https://github.com/freerange/mocha/blob/a7bc1b53ace895503b4b5d4915382aead4632e3e/lib/mocha/api.rb#L18-L22

Upvotes: 1

Related Questions