Module Mocha::ObjectMethods
In: lib/mocha/object.rb
lib/mocha/metaclass.rb
lib/mocha/parameter_matchers/object.rb
lib/mocha/inspect.rb

Methods added all objects to allow mocking and stubbing on real objects.

Methods return a Mocha::Expectation which can be further modified by methods on Mocha::Expectation.

Methods

Public Instance methods

Adds an expectation that a method identified by method_name Symbol must be called exactly once with any parameters. Returns the new expectation which can be further modified by methods on Mocha::Expectation.

  product = Product.new
  product.expects(:save).returns(true)
  assert_equal true, product.save

The original implementation of Product#save is replaced temporarily.

The original implementation of Product#save is restored at the end of the test.

If method_names_vs_return_values is a Hash, an expectation will be set up for each entry using the key as method_name and value as return_value.

  product = Product.new
  product.expects(:valid? => true, :save => true)

  # exactly equivalent to

  product = Product.new
  product.expects(:valid?).returns(true)
  product.expects(:save).returns(true)

Adds an expectation that a method identified by method_name Symbol may be called any number of times with any parameters. Returns the new expectation which can be further modified by methods on Mocha::Expectation.

  product = Product.new
  product.stubs(:save).returns(true)
  assert_equal true, product.save

The original implementation of Product#save is replaced temporarily.

The original implementation of Product#save is restored at the end of the test.

If method_names_vs_return_values is a Hash, an expectation will be set up for each entry using the key as method_name and value as return_value.

  product = Product.new
  product.stubs(:valid? => true, :save => true)

  # exactly equivalent to

  product = Product.new
  product.stubs(:valid?).returns(true)
  product.stubs(:save).returns(true)

Removes the method stub added by calls to expects or stubs. Restores the original behaviour of the method before it was stubbed.

  multiplier = Multiplier.new
  multiplier.double(2) # => 4
  multiplier.stubs(:double).raises
  multiplier.double(2) # => raises exception
  multiplier.unstubs(:double)
  multiplier.double(2) # => 4

The original implementation of Multiplier#double is replaced temporarily.

The original implementation of Multiplier#double is restored when unstub is called.

WARNING: If you unstub a method which still has unsatisfied expectations, you may be removing the only way those expectations can be satisfied. Use unstub with care.

If multiple method_names are supplied, each method is unstubbed.

  multiplier.unstub(:double, :triple)

  # exactly equivalent to

  multiplier.unstub(:double)
  multiplier.unstub(:triple)

[Validate]