Last Updated: February 25, 2016
·
855
· jedschneider

Wisely pick your dates for specs

Whats wrong with this spec?

profile.set_start_date('01/02/2012')
expect(profile.start_date).to eq(Date.parse('01/02/2012')

Well, probably a couple things, but for simplicities sake, lets assume that you are using that Date.parse method in your production code that sets the start date and you are just testing that some process sets the date right. Well the issue is that because you use that method in both the test and the spec, you're certain it is getting set, but it might be getting set one month off without you realizing it. This should be a little better:

expect(profile.start_date.month).to eq(1) #=> fails: expected 1, got 2

So, I would suggest using something that would be an invalid date if the parser doesn't do what you expect to begin with, such that you catch subtle bugs such as this much earlier.

profile.set_start_date = '01/31/2012' #=> internal code throws invalid date error
expect(profile.start_date.month).to eq(1)

Thanks for reading!

2 Responses
Add your response

Why are you testing assignment at all? I assume that set_start_date = '01/02/2012' is actually supposed to be set_start_date('01/02/2012')? Or maybe start_date = '01/02/2012'

Assignment is a language construct and so I would assume it to be correct and thus not worth testing. If you're overriding the assignment operator, I think that's sort of a bad idea because of this problem. I would assume from the code that:

profile.set_start_date = '01/02/2012'
expect(profile.start_date).to eq('01/02/2012')

Would be true... I realize Rails does this all the time, but I think it's bad practice and should be avoided for clarity. Otherwise I agree with the point: "us[ing] that method in both the test and the spec, you're certain it is getting set, but it might be getting set one month off without you realizing it."

over 1 year ago ·

@plukevdh yah coding in coderwall's text editor is obviously prone to error. Was only trying to make the most simple spec snippet that would be marginally understandable without a lot of extraneous code. I would have maybe more accurately said

def magically_transform_start_date_from_string(string)
   @start_date = Date.parse string
end

but, you get the point.

over 1 year ago ·