From: cremes.devlist@... Date: 2006-06-17T22:57:23+09:00 Subject: Re: need help with FlexMock (or mocking in general) On Jun 16, 2006, at 9:31 PM, Jim Weirich wrote: > unknown wrote: >> I'm trying to mock a single method call in a controller I'm testing >> (this isn't a Rails question). I only want to mock the method for >> certain tests while the "real" method continues to function as before >> in the remainder of the tests. I'm trying to figure out how to use >> FlexMock to do this but I'm coming up empty. > > The first step is to decide what you are testing. Are you testing the > controller, or the UUID class? In this case, it looks like it is the > controller. In fact, it looks like you are specifically testing the > Controller/UUID interaction. Absolutely true. > So, I would recommend something like this. > [snip] > Now, in your test file, cleverly modify the Storage controller > class to > allow you to inject a mock UUID: > > class StorageController > attr_accessor :test_uuid > def get_next_uuid > (@test_uuid || UUID).new > end > end > > (There are several ways of doing this, this is just an ad hoc way that > is simple for one-off situations. If you find yourself doing this a > lot, then you might want to consider a dependency injection > framework). A dependency injection framework? Mmmm... getting a bit beyond my knowledge and experience. Though, come to think of it, I do recall running across a write-up of using a dependency injection framework in Rails instead of the existing Test::Unit stuff. I didn't read the whole paper... I should google for that again. I may need this capability somewhere down the road. > Now, write the tests. I would start off like this: > > class TestStorageControllerUuidInteractionTest < > Test::Unit::TestCase > include FlexMock::TestCase > > def setup > @controller = StorageController.new > @controller.uuid_class = flexmock("uuid") > end This all worked. I had to change "@controller.uuid_class=" to "@controller.test_uuid=" to match the previous accessor setup, but otherwise this all worked right out of the box. Amazing stuff. Every day I learn something new about the dynamism of Ruby. > [snip] > That covers the tests in your example. There are a couple more > tests I > would suggest: (a) Mulitple UUID requests returning different values, > (b) cause a UUID colision, but not so many that the assign fails. But > that's enough for this message. Now that I have the base tests working, I will do as you suggest. > Does this help? Does it ever! When I posted this message I purposefully put "FlexMock" into the title in the hope that you (as the author of it) would notice and answer the question. Thanks very much for doing so! The Flexmock documentation examples didn't cover the case where a class mocked just a single method which is why I was floundering a bit here. After I experiment a bit more and wrap my head around how this is working, I hope you'll accept a documentation patch that illustrates this. cr