我正在尝试为访问a的控制器编写rspec测试 模特集团。
@request.env['HTTP_REFERER'] = group_url(@mock_group) ### Line 49
我明白了:
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'
url_for中的这一行是问题所在;特别是@url是零。
@url.rewrite(rewrite_options(options))
似乎@url在这里初始化了:
def initialize_current_url @url = UrlRewriter.new(request, params.clone) end
答案 0 :(得分:3)
这是因为url_for依赖于在请求处理期间初始化的内容。我假设您的测试看起来像这样:
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失败,因为它发生在get之前。解决此问题的最简单方法是对测试中的网址进行硬编码(即将url\_for(@mock\_group)
更改为"http://test.host/group/1"
)。另一个选择是在调用url_for之前弄清楚如何让@controller初始化@url。我想我之前已经这样做了,但我没有更多的代码,它涉及挖掘action_controller的代码。
答案 1 :(得分:0)