Show Menu
Cheatography

Mocha is a Ruby library for mocking and stubbing. Shamelessly copied from the cheat gem mocha cheat sheet.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Mocking a class method

product = Produc­t.new
Product.expects(:find).with(1).
  returns(product)
assert­_equal product, Produc­t.f­ind(1)

Stub instance methods on real object

prices = [stub(:pence => 1000),
  stub(:pence => 2000)]
product = Produc­t.new
product.stubs(:prices).returns(prices)
assert­_equal [1000, 2000],
  prod­uct.pr­ice­s.c­ollect {|p| p.pence}

Tradit­ional mocking

object = mock()
object.expects(:expe­cte­d_m­ethod).
  with(:p1, :p2).returns(:result)
assert­_equal :result,
  obje­ct.e­xp­ect­ed_­met­hod­(:p1, :p2)
 

Mocking instance method on real object

product = Produc­t.new
product.expects(:save).returns(true)
assert produc­t.save

Stub method on all instances of class

Product.any_in­stance.stubs(:name).
  returns('stub­bed­_name')
product = Produc­t.new
assert­_equal 'stubb­ed_­name',
  prod­uct.name

Shortcuts

object = stub(:method1 => :result1,
  :method2 => :result2)
assert­_equal :result1, object.me­thod1
assert­_equal :result2, object.me­thod2
 

Expection Methods

at_least(minimum)
Modifies expect­ation so that the expected method must be called at least a minimum number of times.
at_lea­st_once
Modifies expect­ation so that the expected method must be called at least once.
never
Modifies expect­ation so that the expected method must never be called.
raises(exception = Runtim­eError, message = nil)
Modifies expect­ation so that when the expected method is called, it raises the specified exception with the specified message.
returns(value)
Modifies expect­ation so that when the expected method is called, it returns the specified value.
times(range)
Modifies expect­ation so that the number of calls to the expected method must be within a specific range.
with(*argu­ments, &b­lock)
Modifies expect­ation so that the expected method must be called with specified arguments.
yields(*para­meters)
Modifies expect­ation so that when the expected method is called, it yields with the specified parame­ters.