Thursday, October 2, 2008

undefined method url_for in rails functional test

When attempting to use url_for(options) method (which works fine in controllers and views) inside a functional test (Rails 2.1.1) I'd get 'undefined method url_for...' exception. This was a standard functional test so I thought these things would be there.

To fix it, inside your functional test class definition do something like this:
class GroupControllerTest < Test::Unit::TestCase
# Note: to make sure url_for works in a functional test, include the two files below!
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::TagHelper
I wonder if there's a nicer way to do this?

3 comments:

Nick said...

You should try inheriting your test class from "ActionController::TestCase" rather than Test::Unit. That should pull in more things that will be useful in functional tests:

class GroupControllerTest < ActionController::TestCase

Alex said...

in ruby (and rails in general) classes are never closed to modification. You can add the following to the end of test_helper.rb if you find yourself using these helpers to test your views a lot:

==test_helper.rb==
class ActionController::TestCase
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::TagHelper
end

Zach Dwiel said...

I also had to include the following to get it to work due to an undefined method polymorphic_path:

include ActionController::PolymorphicRoutes