From: Robert Dober Date: 2006-05-25T00:19:11+09:00 Subject: Re: Overriding Time.now ------=_Part_175514_19412308.1148483947821 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 5/24/06, Molitor, Stephen L wrote: > > One caution: I did what Robert suggested a while back. It works > perfectly, but does wreak havoc with Test::Unit and rake test times > reporting. Tests can appear to finish before they've started, etc. I en= ded > up creating a CurrentTime class: > > class CurrentTime > @@now =3D nil > > def now > @@now || Time.now > end > > def now=3D(new_time) > @@now =3D new_time > end > end > > I changed my code to use CurrentTime.now instead of Time.now. Test::Unit= , > rake and friends still use Time.now, so they don't get messed up. In my > unit test I mock out the time by calling CurrentTime.now=3D. Crude but i= t > works. Yup you have to change the code to be tested, not the best idea. I guess you can avoid this by redefining now only in the class to be tested= , please note I did not hang anybody (by not redefining Time.now) just gave you the rope to hang yourself (by redefining Time.now). Now (pun intended) I believe that you can redefine Time.now in the scope where you need it without interfering with Test::Unit, well you are still administring the code you test somehow. Neverheless that might be the cleanest approach, I would be glad to have a better one suggested though. Cheers Robert Steve > > -----Original Message----- > From: Robert MannI [mailto:robmnl@gmail.com] > Sent: Wednesday, May 24, 2006 9:37 AM > To: ruby-talk ML > Subject: Re: Overriding Time.now > > Thanks alot Robert, that'll do it > > > > Rob > > On 5/24/06, Robert Dober wrote: > > > > On 5/24/06, Robert MannI wrote: > > > > > > Hello! > > > > > > I have a unit test where I need to simulate a different system time. > > > > > > Hence I need Time.now to return a different time than now, say, now > > > + 1 month > > > > > > How can I do this? > > > > > > I tried aliasing Time now, but I don't know how to alias class > methods. > > > > > > class Time > > > alias_method 'self.original_now', 'self.now' > > > end > > > > > > How can I alias this --or-- is there any better way to simulate a > > > different time on calling Time.now? > > > > > > > > > Tips and ideas are greatly appreciated, Rob > > > > > > Hi > > > > class Time > > class << self > > alias_method :n, :now > > end > > end > > > > hope that helps > > Cheers > > Robert > > > > > > -- > > Deux choses sont infinies : l'univers et la b=EAtise humaine ; en ce qu= i > > concerne l'univers, je n'en ai pas acquis la certitude absolue. > > > > - Albert Einstein > > > > > > --=20 Deux choses sont infinies : l'univers et la b=EAtise humaine ; en ce qui concerne l'univers, je n'en ai pas acquis la certitude absolue. - Albert Einstein ------=_Part_175514_19412308.1148483947821--