From e7f66fb2ba8e7368d4b40587496a9309714405f5 Mon Sep 17 00:00:00 2001 From: Daniel Colson Date: Fri, 26 Oct 2018 14:47:44 -0400 Subject: [PATCH] Set timestamps after clearing changes Rather than redefining #created_at and #updated_at, we can use the existing methods and just set them if there aren't already values present. We need to do this after clearing changes information, otherwise the times end up getting converted to the wrong zone. --- lib/factory_bot/strategy/stub.rb | 52 ++++++++++++++------------------ 1 file changed, 23 insertions(+), 29 deletions(-) diff --git a/lib/factory_bot/strategy/stub.rb b/lib/factory_bot/strategy/stub.rb index 3f4f6b9..ead07fa 100644 --- a/lib/factory_bot/strategy/stub.rb +++ b/lib/factory_bot/strategy/stub.rb @@ -32,6 +32,7 @@ module FactoryBot evaluation.object.tap do |instance| stub_database_interaction_on_result(instance) clear_changes_information(instance) + set_timestamps(instance) evaluation.notify(:after_stub, instance) end end @@ -64,35 +65,6 @@ module FactoryBot end end end - - created_at_missing_default = result_instance.respond_to?(:created_at) && !result_instance.created_at - - if created_at_missing_default - result_instance.instance_eval do - def created_at - @created_at ||= Time.now.in_time_zone - end - - def created_at=(date) - @created_at = date - end - end - end - - has_updated_at = result_instance.respond_to?(:updated_at) - updated_at_no_default = has_updated_at && !result_instance.updated_at - - if updated_at_no_default - result_instance.instance_eval do - def updated_at - @updated_at ||= Time.current - end - - def updated_at=(date) - @updated_at = date - end - end - end end def clear_changes_information(result_instance) @@ -100,6 +72,28 @@ module FactoryBot result_instance.clear_changes_information end end + + def set_timestamps(result_instance) + if missing_created_at?(result_instance) + result_instance.created_at = Time.current + end + + if missing_updated_at?(result_instance) + result_instance.updated_at = Time.current + end + end + + def missing_created_at?(result_instance) + result_instance.respond_to?(:created_at) && + result_instance.respond_to?(:created_at=) && + result_instance.created_at.blank? + end + + def missing_updated_at?(result_instance) + result_instance.respond_to?(:updated_at) && + result_instance.respond_to?(:updated_at=) && + result_instance.updated_at.blank? + end end end end