Method: Mocha::ObjectMethods#stubs

Defined in:
lib/mocha/object_methods.rb

#stubs(method_name) ⇒ Expectation #stubs(stubbed_methods_vs_return_values) ⇒ Expectation

Adds an expectation that the specified method may be called any number of times with any parameters.

The original implementation of the method is replaced during the test and then restored at the end of the test. The temporary replacement method has the same visibility as the original method.

Examples:

Setting up a stubbed methods on a non-mock object.

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

Setting up multiple stubbed methods on a non-mock object.

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)

Raises:

  • (StubbingError)

    if attempting to stub method which is not allowed.

See Also:



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/mocha/object_methods.rb', line 134

def stubs(stubbed_methods_vs_return_values)
  if frozen?
    raise StubbingError.new("can't stub method on frozen object: #{mocha_inspect}", caller)
  end

  expectation = nil
  mockery = Mocha::Mockery.instance
  iterator = ArgumentIterator.new(stubbed_methods_vs_return_values)
  iterator.each do |method_name, *args|
    mockery.on_stubbing(self, method_name)
    method = stubba_method.new(stubba_object, method_name)
    mockery.stubba.stub(method)
    expectation = mocha.stubs(method_name, caller)
    expectation.returns(args.shift) unless args.empty?
  end
  expectation
end