Wednesday, April 9, 2008

date_select functional testing (another gotcha)

Here's a quick sympathy post for those who are relatively new to the Rails framework.

Situation:

You're trying to test a form post that uses the "date_select" helper tag and you've noticed that rails is somehow automagically transforming the three fields in the form into one attribute in the request, and you don't know how to write a functional test that has everything formatted correctly in order to produce a valid date on the other side. You've googled for help and found not many people have addressed this.

Solution:

The reason most people haven't addressed this problem is that the solution is so very simple that most people haven't even run into it as a "problem" per se. But if you found this post because you haven't solved the "problem" yet, than you might be a little like me; you might have decided to think about the problem so long that you've convinced yourself that you don't know how you'll accomplish it. So I have two solutions for you, one for your immediate problem of how to set up a post parameter representing a date in a functional test, and another for your (my) problem with overthinking things to death. First, the code:


class some_controller_test < ActionController::TestCase
def test_post_form_with_date
post :action_name, {:model_name=>{:date_field => 5.days.since.utc.to_s}}
assert #...anything you need to check....#
end
end



Yes, that's right, all it really took was just setting up a date object and calling "to_s" (this solution worked for me, if anyone else has anything slicker they'd like to post feel free to do so below). It was really the obvious thing to do in the first place, but I was so sure I was going to have to work around the 3-field nature of the date_select helper method, that I didn't even try it out first; and therin lies the second solution. Try it out. Just try SOMETHING and you'll be one step closer than nowhere, which is were you were before. ;-)

No comments: