From: Jim Weirich Date: 2006-03-21T00:57:50+09:00 Subject: Re: Library for Mocking Thiago Arrais wrote: > Rubysts, > > I am looking for a library for mocking objects. [...] > FlexMock works by creating a full-blown, ready-to-use, suited-to-your > needs mock object in one method call (namely FlexMock.use). Then you > can just inject it into your tested object and use it. Actually, you still need to specify the behavior of the mock. The "use" module method just ensures that that mock_verify is properly called at the end of the test. FlexMock currently has two ways of specifying behavior: (1) the original "mock_handles" way and (2) the JMock-like "should_receive" way. > [...] I prefer the record/playback > metaphor, where you actually call the methods you want to be called on > the record phase and then the object under test is responsible for > making the expected calls on playback phase. Currently, FlexMock does not support a recording mode. But one could easily be added: class FlexMock class Recorder def initialize(mock) @mock = mock end def method_missing(sym, *args, &block) @mock.should_receive(sym).and_return(&block) end end def should_expect yield Recorder.new(self) end end This allows you to do the following: FlexMock.use("socket") do |mock_socket| mock_socket.should_expect do |recording_socket| recording_socket.addr { ["AF_INET", 23, "localhost", "127.0.0.1"] } recording_socket.getsocketopt { DEFAULT_SOCKET_OPTS } end # Testing code goes here that uses mock_socket and # calls addr and getsocketopt. end There are some open questions. (1) how are arguments to the mock method validated? (exact match, constraints, no validation?) (2) is the order of the messages important? The implementation provided above does no argument validation (but the arguments are sent to the recording block for hand validation) and the order of method calls is ignored. However, I think automatic parameter validation could be added without too much effort. If there is sufficient interest in a recording interface to MockFlex, I am willing to consider it for inclusion in the library. -- -- Jim Weirich -- Posted via http://www.ruby-forum.com/.