views:

387

answers:

2

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
A: 

Look at this. I think it is relevant.

http://jakescruggs.blogspot.com/2008/11/if-you-use-mocha-and-rspec-then-read.html

Tim Harding
+3  A: 

This happens because url_for depends on stuff that's initialized during request processing. I assume your test looks something like this:

it "should do whatever when referrer is group thing" do
  @request.env["HTTP_REFERER"] = url_for(@mock_group)
  get :some_action
  "something".should == "something"
end

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.

Matt Burke