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.
我的模型类上有一个before_save过滤器,它将日期字段设置为未来日期,以保证数据的完整性。
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
?
这非常有效,除了单元测试。我想设置一个测试场景,其中包括将此日期字段设置为过去的日期。我无法使用ActiveRecord执行此操作,因为调用了before_save过滤器并将日期更新为将来的日期。是使用ActiveRecord :: Base :: connection.update执行原始SQL的最佳方法吗?
3 个解决方案
#1
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/
#2
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.
它可能被认为是一个黑客攻击,但你总是可以在单元测试中重新打开你的模型类并覆盖你的before_save过滤器的实现。
#3
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
它似乎应该做的唯一测试是确保当你尝试在过去保存日期时它正确处理它
#1
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/
#2
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.
它可能被认为是一个黑客攻击,但你总是可以在单元测试中重新打开你的模型类并覆盖你的before_save过滤器的实现。
#3
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
它似乎应该做的唯一测试是确保当你尝试在过去保存日期时它正确处理它