Reputation: 12663
In a Rails app I have a model attribute that sets a datetime when the user performs an action.
What is the best way to test for this functionality, without being too brittle?
for example, I have
it "should set the uploaded time" do
@model.uploaded_at.should == DateTime.now.new_offset(0)
end
My test is failing when it should pass, with
expected: Thu, 24 May 2012 10:32:50 +0000
got: Thu, 24 May 2012 10:32:50 UTC +00:00
So my questions are:
How should I define DateTime.now.new_offset(0)
so that the UTC
marker is expected?
I can see this test potentially failing due to
the passage of time. For example: factory get created, tests are
run, 1 second later it "should set the uploaded time"
is run,
test fails due to 1 second difference. Is there a better way to test
this?
Thanks for any tips that would help me learn this.
Upvotes: 0
Views: 674
Reputation: 833
For your second question, if you don't want to add another gem (timecop), you can stub the date (DateTime.stub(:now).and_return :whatever
) or base your test on the fact that uploaded_at
changed (@model.uploaded_at.should_not == the_previous_uploaded_at_value
)
Upvotes: 1
Reputation: 5437
there is timecop for that purpose https://github.com/jtrupiano/timecop
Upvotes: 3