Foo_url (mock_foo) sometimes doesn't work in rspec tests

I am trying to write an rspec test for a controller that accesses a model.

@ 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 null.

@ url.rewrite (rewrite_options (options))

And it seems like @url is being initialized here:

def initialize_current_url
  @url = UrlRewriter.new (request, params.clone)
end
+1


source to share


2 answers


This is because url_for depends on what was initialized while processing the request. 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 getting. The easiest way to solve the problem is to hard-code the url in your test (i.e. change url\_for(@mock\_group)

to "http://test.host/group/1"

). Another option is to figure out how to get @controller to initialize @url before calling url_for. I think I have done this before, but I have no more code and it has to do with the action_controller code breakout.

+3


source


Look at this. I think this is relevant.



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

0


source







All Articles