Olly
Olly

Reputation: 7758

Overriding a before_save filter for testing purposes in Rails

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?

Upvotes: 0

Views: 994

Answers (3)

ErsatzRyan
ErsatzRyan

Reputation: 3043

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/

Upvotes: 2

ErsatzRyan
ErsatzRyan

Reputation: 3043

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

Upvotes: 0

John Topley
John Topley

Reputation: 115372

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.

Upvotes: 0

Related Questions