.

Fun with TimeStamps |

I can’t tell yet if this is an issue I just never ran into or if it has something to do with running Edge Rails (more testing and I’ll know)

Anyway I ran into a problem today working on some code were I actually need to set the created_at/updated_at fields for a given object. This made it easier to make sure that the search returned the right objects.

I kept doing

my_obj = MyClass.new(:name => "hello", :created_at => Time.gm(2006,1,1,10,12,13),
:updated_at => Time.gm(2006,1,1,10,12,13))

The updated_at always got set to now(). Which defeats the purpose. Turns out there is a simple way to turn off the Rails magic

MyClass.record_timestamps = false

That line of code turns off auto settting the magic fields. This let me set the stamps to what I wanted - and then I just turned it back on after the creation was done. (if you don’t it will be turned off for all tests which is probably not what you want.)

You can also add this if you have one class you never want to use auto timestamping

class MyClass < ActiveRecord::Base
self.record_timestamps = false
end

The above is from active_record/timestamp.rb

Just one of many nooks and cranies I’ve fallen into this week. If I can I’ll put up my notes on the joys of Monkey Patching with web services.

4 Responses to 'Fun with TimeStamps'
  1. ian:

    I’m curious as to why you needed to manually set these fields? If you really wanted some custom control, why not just create your own timestamp field and use it?

  2. HeadGeek:

    That’s easy - I was actually setting up data in a unit test to make sure that method that searchs for objects based on a given date actually works properly.

  3. ian:

    Ok. I guess this was not data that was already coming from fixtures then.

  4. HeadGeek:

    it wasn’t. That’s probably why I hadn’t run into it before. One of the articles on testing I was reading recently talked about creating the data needed to test in the test you were working on.,

    I’m not sure I’m switching over - but that is what I was doing when I was writing this test.

Leave a Reply

Moderation Active: Old stuff here... Therefore your comment on this post will be moderated (i.e. don't submit twice !)

    Categories
    Archives

    .