Ben Downey
Ben Downey

Reputation: 2665

How to Test an Array of Date Objects Is Correct

I'm trying to I take an array like this:

 MY_ARRAY = ["Jan 31, 2013", "Feb 28, 2013", "Mar 31, 2013"] 

and then turn it into dates:

def array_as_date_objects
  MY_ARRAY.map { |month| Date.parse(month)}
end

which yields this:

 [#<Date: 2013-01-31 (4912645/2,0,2299161)>, #<Date: 2013-02-28 (4912703/2,0,2299161)>, #<Date: 2013-03-31 (4912763/2,0,2299161)>]

Great. But I also want to test that this array of date objects is what I expect it to be. How would I do that?

I had hoped something like this would work, but the hashtag comments out the remaining info.

 MyClass.new.refined_schedule.should == :[#<Date: 2013-01-31 (4912645/2,0,2299161)>, #<Date: 2013-02-28 (4912703/2,0,2299161)>, #<Date: 2013-03-31 (4912763/2,0,2299161)>]

Edit: So just to give more info on my situation, my main concern is really how to stub this array. I don't need to trust that Ruby created the array correctly, I just need to stub the method correctly. Sorry for not being clear.

describe "#final_schedule" do
  it "generates an array of pay dates that do not fall on any weekend day" do
    test_schedule = MyClass.new
    test_schedule.stub(:refined_schedule) { [#<Date: 2013-01-31 (4912645/2,0,2299161)>, #<Date: 2013-02-28 (4912703/2,0,2299161)>, #<Date: 2013-03-31 (4912763/2,0,2299161)> ] } 
    test_schedule.final_schedule.should == [ "Thursday, Jan 31, 2013", "Thursday, Feb 28, 2013","Sunday, Mar 31, 2013"]
  end
 end

Upvotes: 0

Views: 65

Answers (2)

Draco Ater
Draco Ater

Reputation: 21226

#<Date: 2013-01-31 (4912645/2,0,2299161)>

This is a printable representation of an object. You cannot just write it and hope that ruby understands it as a date. Date object is created with constructor:

Date.new( 2013, 1, 31 )

So if you want to test if parsing result was right (which sometimes is necessary, for example for these formats: mm/dd/yy vs dd/mm/yy), you should do something like that:

MyClass.new.refined_schedule.should == [Date.new( 2013, 1, 31 ), Date.new( 2013, 2, 28 ),..]

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160551

When I write a test of my code, I look to see if I got an array back, and that all the contents of that array are of a certain type.

Whether those individual elements are correctly converted from strings to DateTime objects via parsing, doesn't concern me because that particular test occurs during the tests of the language when it's compiled and is part of the unit tests for DateTime.

Sure, we can be completely paranoid, or anal, and test every aspect of the code from our methods down to the atomic level, and be convinced everything works correctly, or we can trust that the language's developers are doing their part, and build upon that. So far I haven't had a reason to suspect they are failing on their part, so I can take the easier path.

Upvotes: 1

Related Questions