views:

377

answers:

3

I have a before_save filter on my model class which sets a date field to a future date to guarantee the integrity of the data.

This works really well except with it comes to unit testing. I'd like to set up a test scenario which involves setting this date field to a date in the past. I can't do this using ActiveRecord because the before_save filter is called and the date is updated to a future date. Is the best way to do this to execute raw SQL using ActiveRecord::Base::connection.update?

A: 

It could be considered a bit of a hack, but you could always re-open your model class within your unit test and override the implementation of your before_save filter.

John Topley
A: 

If you do not allow that to happen why do you need to test for when it has happened?

What i mean is if you never allow a date in the past to be saved into that model then you should never have that so what is there to test?

the only test it seems should be done is to make sure that when you try to save a date in the past it handles it correctly

ErsatzRyan
The test I'm writing is not for this model, but for a background worker class which uses the model. When the local time is greater than this date on the model (which happens after 7 days in our app) then the background worker performs a job on the model. Since I'm testing the background worker, I need to create a scenario whereby the model date has passed.
Olly
+2  A: 

Maybe utilizing a mock object would be best. For a quick intro to mock objects read

http://erikonrails.wordpress.com/2008/05/07/how-to-use-mock-objects/

ErsatzRyan