Forum: Ruby mock object standard?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
8a4c59ead55636dcf3f82fe0e545f5ed?d=identicon&s=25 byronsalty (Guest)
on 2007-06-18 07:57
(Received via mailing list)
I see a lot of discussion from a few years ago about Mock objects but
I'm unclear if there was any decision made. What is everyone using for

I see a lot of Java based mock software ported over and it didn't look
like the full power of Ruby was utilized. I'm speaking as someone who
has only read through the blogs today so if I'm off base just send me
plenty of hate responses.

I personally like Java's EasyMock and I found that the usage can be
cleaned up nicely in Ruby. Here's a comparison of the usage of the
real EasyMock and class I just created to do the same thing for me.

Given a fictious DAO which retrieves and updates user names by id:

// setup
private MockControl userDaoControl =
private UserDao userDao = (UserDao) userDaoControl.getMock();

// training phase
userDao.update_name(-1, "Bobby");
userDaoControl.setThrowable(new RuntimeException("user not found"));

// now use the mock
assertEquals("Bob", userDao.find_name(1));
  // i don't know an easy way to test exceptions in junit3.8
  // i'll spare you the nasty try/fail/catch that is generally done.

# setup - note no interface/class pass in necessary
userDao =

# training
userDao.expects do |mock|
  mock.find_name(1) {return "Bob"}
  mock.update_name(-1, "Bobby") {raise "user not found"}

# use
assert_equal "Bob", userDao.find_name(1)
assert_raise(RuntimeError) { userDao.update_name(-1, "Bobby")}


The amazing thing is the code for this is ~40 lines. I say this only
to point out that duck typing rocks for mock objects.

The use of blocks to specify what should happen when a method is
called is so nice as it allows arbitrary code to be executed. You
could specify multiple things to happen before the return if desired
allowing you to make mocks arbitrarily complicated. (Although I
couldn't get "yield" to work since it seems to be a well known problem
with "call" on a Proc like: lambda {yield "hello"})

The use of a block to specify the training phase is also nice, I
believe. Thereafter this mock should behave like the object being
mocked as specified.

Anyway - let me know if I'm re-inventing the wheel or not. I'll likely
post the code on my blog tomorrow after some sleep and another shot at
the yield issue.

- Byron
6bbff80f9e6358139859ba1a40204cad?d=identicon&s=25 Paul McMahon (Guest)
on 2007-06-18 08:54
(Received via mailing list)
Have you looked at Flex Mock?
82a61255b4090da7d3619f870b0794dc?d=identicon&s=25 James Mead (floehopper)
on 2007-06-18 10:01
(Received via mailing list)
This topic is locked and can not be replied to.