Skip to content

Instantly share code, notes, and snippets.

@shime
Last active March 15, 2021 19:26
Show Gist options
  • Save shime/9930893 to your computer and use it in GitHub Desktop.
Save shime/9930893 to your computer and use it in GitHub Desktop.
comparing dates and times in RSpec

What is this?

How do you compare date/times in RSpec?

If you do this

expect(Time.now.to_i).to eq Time.new(2014, 4, 2).to_i

and you usually use more human format of expressing time, than just spitting out the miliseconds since January 1, 1970 - I've got some bad news for you.

Have you ever wondered what does this mean?

1) time comparison doesn't pass for different time
     Failure/Error: expect(Time.now.to_i).to eq Time.new(2014, 4, 2).to_i
       
       expected: 1396389600
            got: 1396430562

Yes, me too - these miliseconds are not that expressive...

With this gist, that will change into:

  1) time comparison doesn't pass for different time
     Failure/Error: expect(Time.now).to be_the_same_time_as Time.new(2014, 4, 2)
       expected 2014-04-02 11:28:41 +0200 to be the same time as 2014-04-02 00:00:00 +0200

Much nicer, right?

Don't believe me?

Run this

bash < <( curl -fsSL https://gist.githubusercontent.com/shime/9930893/raw/try.sh )

Trust me, I'm just a random guy from the interwebz!

RSpec::Matchers.define :be_the_same_time_as do |expected|
match do |actual|
expect(expected.strftime("%d-%m-%Y %H:%M:%S")).to eq(actual.strftime("%d-%m-%Y %H:%M:%S"))
end
end
describe "time comparison" do
it "passes for equal dates" do
expect(Time.new(2014, 4, 2)).to be_the_same_time_as Time.new(2014, 4, 2)
end
it "passes for equal time" do
expect(Time.now).to be_the_same_time_as Time.now
end
it "doesn't pass for different time" do
expect(Time.now).to_not be_the_same_time_as Time.new(2014, 4, 2)
end
end
curl -fsSL https://gist.githubusercontent.com/shime/9930893/raw/example_spec.rb > /tmp/example_spec.rb
rspec -c /tmp/example_spec.rb
@catkins
Copy link

catkins commented Nov 3, 2014

Awesome. This just saved me a whole bunch of heartache.

@pencilcheck
Copy link

Your solution doesn't work for me, as I am comparing DateTime objects with different time zome data. Just forked your gist and make a version that takes care of that.

https://gist.github.com/pencilcheck/9385e909fd54b3a0adf0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment