Reputation: 10358
In rspec, we would like to check if a date field has been updated by the update in invoice controller. Here is the code:
it "should have corp head id and approve date" do
cust = Factory(:customer)
u = Factory(:user)
rfq = Factory(:rfq, :sales_id => u.id, :customer_id => cust.id, :sales_id => u.id)
q = Factory(:quote, :rfq_id => rfq.id)
i = Factory(:invoice, :quote_id => q.id, :approved_by_corp_head => nil )
session[:corp_head] = true
session[:user_id] = u.id
get 'update', :id => i.id, :quote_id => q.id, :invoice => {:paid_out => true, :approved_by_corp_head => true}
i.reload.corp_head_id.should == u.id
i.reload.approve_date_corp_head.strftime("%Y/%m/%d").should == Time.now.strftime("%Y/%m/%d")
end
In invoice controller, there is a line to record the Time.now:
invoice.approve_date_corp_head = Time.now
It is odd that sometimes line i.reload.approve_date_corp_head.strftime("%Y/%m/%d").should == Time.now.strftime("%Y/%m/%d")
will fail saying that there is one day difference between dates compared. It seems that the line would fail when we run rspec late at the night (before 12am though). We haven't seen failure early in the morning.
Anyone has idea about this odd behavior? Thanks so much.
Upvotes: 3
Views: 372
Reputation: 787
Change the expectation in the spec to
i.reload.approve_date_corp_head.strftime("%Y/%m/%d").should == Time.now.utc.strftime("%Y/%m/%d")
I would also echo Shaun's recommendation to use TimeCop
Upvotes: 3
Reputation: 6581
First I would recommend that you ensure that all times that you are testing against are in UTC. That way it stops any timezone differences, especially if you are in a timezone further from GMT and it is either morning or evening.
Second, I'd recommend using TimeCop to stop time, thus if you put a sleep in just before the .should step, it would still give the correct answer if you run over the unit of time.
Upvotes: 3