Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec - how to compare to an actual DateTime in the expect?

Tags:

ruby

rspec

My rspec:

it "can show the current month name" do
  expect(Calendar.create_date_using_month(1)).to eq '2000-01-01 00:00:00 -0500'
end

fails with:

expected: "2000-01-01 00:00:00 -0500"
     got: 2000-01-01 00:00:00 -0500

For my code:

def self.create_date_using_month(n)
  Time.new(2000,n,1)
end

Should/can I change the RSpec so that I am comparing to an actual string not a date?

I tried: Date.strptime("{ 2000, 1, 1 }", "{ %Y, %m, %d }")

but that gives me

   expected: #<Date: 2000-01-01 ((2451545j,0s,0n),+0s,2299161j)>
        got: 2000-01-01 00:00:00 -0500
like image 545
Michael Durrant Avatar asked Oct 16 '13 14:10

Michael Durrant


1 Answers

I'm a bit confused about what exactly you're testing here. If create_data_using_month creates a Time object, you should compare it with a Time object.

This message:

expected: "2000-01-01 00:00:00 -0500"
     got: 2000-01-01 00:00:00 -0500 

is telling you it expected the literal string with the date, but got an object whose to_s happens to be the same.

So I guess you could "fix" it, by changing this:

it "can show the current month name" do
  expect(Calendar.create_date_using_month(1).to_s).to eq '2000-01-01 00:00:00 -0500'
end

But that seems odd, is that what you want? You'll also likely have issues if you test on a machine with different time zone settings.

I'd just do this:

it "can show the current month name" do
  expect(Calendar.create_date_using_month(1)).to eq Time.new(2000, 1, 1)
end

which passes for me just fine.

like image 175
Nick Veys Avatar answered Sep 25 '22 05:09

Nick Veys