Skip to content

Commit cc98380

Browse files
authored
fix: build_stubbed timestamps are different (#1653)
Factories on entities with created_at and updated_at assign a slightly different time for each, because it calls Time.now twice. This fix ensures they will be assigned the exact same time.
1 parent 776838c commit cc98380

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

lib/factory_bot/strategy/stub.rb

+4-2
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,14 @@ def clear_changes_information(result_instance)
102102
end
103103

104104
def set_timestamps(result_instance)
105+
timestamp = Time.current
106+
105107
if missing_created_at?(result_instance)
106-
result_instance.created_at = Time.current
108+
result_instance.created_at = timestamp
107109
end
108110

109111
if missing_updated_at?(result_instance)
110-
result_instance.updated_at = Time.current
112+
result_instance.updated_at = timestamp
111113
end
112114
end
113115

spec/acceptance/stub_spec.rb

+18
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,24 @@
2929
end
3030
end
3131

32+
describe "a stubbed instance with timestamps" do
33+
include FactoryBot::Syntax::Methods
34+
35+
before do
36+
define_model("ModelWithTimestamps", created_at: :datetime, updated_at: :datetime)
37+
38+
FactoryBot.define do
39+
factory :model_with_timestamps
40+
end
41+
end
42+
43+
subject { build_stubbed(:model_with_timestamps) }
44+
45+
it "assigns the exact same datetime" do
46+
expect(subject.created_at).to eq(subject.updated_at)
47+
end
48+
end
49+
3250
describe "a stubbed instance overriding strategy" do
3351
include FactoryBot::Syntax::Methods
3452

0 commit comments

Comments
 (0)