All notes
Mocha

Intro

Mocha doc.

Expectation



##### with

object = mock()
object.expects(:expected_method).with(:param1, :param2)
object.expected_method(:param1, :param2)
# => verify succeeds

object = mock()
object.expects(:expected_method).with(:param1, :param2)
object.expected_method(:param3)
# => verify fails

# Flexible argument matching
# http://blog.danielwellman.com/2010/01/flexible-argument-matching-with-mocha.html
processor.expects(:order).with(:payment => :credit_card, :delivery => :express, :group => :separate)
processor.expects(:order).with(has_key(:payment))
# If you are interested in both the key and value, you could use has_entry, or the alternate has_entries:
processor.expects(:order).with(has_entry(:payment => :credit_card))
processor.expects(:order).with(Not(has_key(:emergency_order)))
processor.expects(:order).with(any_of(includes(:delivery), has_key(:shipping)))
# See the Mocha::ParameterMatchers for more detail.

##### never
object = mock()
object.expects(:expected_method).never
object.expected_method # => unexpected invocation

object = mock()
object.expects(:expected_method).never # => verify succeeds

##### once
object = mock()
object.expects(:expected_method).once
object.expected_method
# => verify succeeds

##### times

object = mock()
object.expects(:expected_method).times(3)
3.times { object.expected_method } # => verify succeeds

##### twice

object = mock()
object.expects(:expected_method).twice
object.expected_method
object.expected_method

Clearing expects using mocha

groups.google.com.

See "mocha/lib/mocha/hooks.rb".


mocha_setup
# Write your expectations....
mocha_verify
mocha_teardown


# You can call
mocha_teardown

# but that might do more than you wanted... so there's the alternative of
Mocha::Mockery.instance.stubba.unstub_all

# or... the even more specific...
Mocha::Mockery.instance.stubba.stubba_methods.each do |meth|
  if meth.stubbee == Date && meth.method == "today"
    meth.unstub
  end
end

Stubs



object = stub()
object.stubs(:expected_method).raises(Exception).then.returns(2, 3)
object.expected_method # => raises exception of class Exception1
object.expected_method # => 2
object.expected_method # => 3

object = stub()
object.stubs(:expected_method).throws(:done).then.returns(2, 3)
object.expected_method # => throws :done
object.expected_method # => 2
object.expected_method # => 3