I am trying to write an rspec test for a controller that accesses a
model Group.
@request.env['HTTP_REFERER'] = group_url(@mock_group) ### Line 49
I get this:
NoMethodError in 'ActsController responding to create should redirect to :back' You have a nil object when you didn't expect it! The error occurred while evaluating nil.rewrite /Library/Ruby/Gems/1.8/gems/actionpack-2.1.0/lib/action_controller/base.rb:621:in `url_for' (eval):17:in `group_url' /Library/Ruby/Gems/1.8/gems/actionpack-2.1.0/lib/action_controller/test_process.rb:464:in `send!' /Library/Ruby/Gems/1.8/gems/actionpack-2.1.0/lib/action_controller/test_process.rb:464:in `method_missing'
This line in url_for is the problem; specfically @url is nil.
@url.rewrite(rewrite_options(options))
And it seems that @url is initialized here:
def initialize_current_url @url = UrlRewriter.new(request, params.clone) end
Best Answer
This happens because url_for depends on stuff that's initialized during request processing. I assume your test looks something like this:
url_for fails because it happens before the get. The easiest way to resolve the problem is to hard-code the URL in your test (i.e. change
url\_for(@mock\_group)
to"http://test.host/group/1"
). The other option is to figure out how to get @controller to initialize @url before you call url_for. I think I've done that before, but I don't have the code around any more and it involved digging through action_controller's code.