Home > OS >  What is the fraction at the end of datetimes in rspec?
What is the fraction at the end of datetimes in rspec?

Time:09-13

I was doing some testing with rSpec, when I wanted to test if a job gets queued at the correct time. For that I queued the task at 2.hours.from_now and then checked it with .at(2.hours.from_now). I quickly realised my mistake and changed that to a variable which fixed the test, but I realised that the test checked for at xxxx-xx-xx xx:xx:xx 721891/1048576 xxxx. Now I am left wondering what the 721891/1048576 exactly does. I found out that 1048576 byte are one Mebibyte. Is it possible that the fraction at the end simply is further precision of the moment, but instead of x/1048576 it shows 1048576 due to the precision being 2^20? Additional information: The used db is psql

CodePudding user response:

It seems to be the way Time#inspect works if the fractional (decimal) part of the subsecond is longer than 9 digits:

Time.new(2022, 1, 1, 0, 0, 1/1_000_000_000r, 'UTC')
#=> 2022-01-01 00:00:00.000000001 UTC

Time.new(2022, 1, 1, 0, 0, 1/10_000_000_000r, 'UTC')
#=> 2022-01-01 00:00:00 1/10000000000 UTC

or if it doesn't have a (finite) decimal representation:

Time.new(2022, 1, 1, 0, 0, 2/3r, 'UTC')
#=> 2022-01-01 00:00:00 2/3 UTC

Now I am left wondering what the 721891/1048576 exactly does.

Your 721891/1048576 is equivalent to ~0.688 seconds, it doesn't have any other special meaning.

The rational number could be the result of passing the time's floating point representation back to Time.at:

t = Time.at(1640995200, 688449)
#=> 2022-01-01 01:00:00.688449  0100

t.to_f
#=> 1640995200.688449

Time.at(1640995200.688449)
#=> 2022-01-01 01:00:00 721891/1048576  0100

This is a common mistake when working with subseconds in Ruby.

  • Related