如何使用application_helper_spec.rb中的特定URL测试请求对象?

| 我在application_helper.rb中定义了一个方法,该方法根据当前请求返回规范的URL。如何模拟或以其他方式指定控制器的完整URL?
# spec/helpers/application_helper_spec.rb
describe \"#canonical_url\" do
  it \"should return a path to an asset that includes the asset_host\" do
    # Given: \"http://www.foo.com:80/asdf.asdf?asdf=asdf\"
    helper.canonical_url().should eq(\"http://www.foo.com/asdf.asdf\")
  end
end

# app/helpers/application_helper.rb
def canonical_url
  \"#{request.protocol}#{request.host}#{(request.port == 80) ? \"\" : request.port_string}#{request.path}\"
end
编辑: 最终,我想测试canonical_url()是否为一堆不同的URL返回正确的字符串,其中一些带有端口,一些不带w / o,有些带有查询字符串,有些带有路径,等等。最终目标。我想既显式地存根/模拟/任何初始URL,然后显式地在匹配器中设置期望值。我希望能够在一个呼叫中完成此操作,即ѭ1this或
request = ActionController::TestRequest.new :url => \'http://www.foo.com:80/asdf.asdf?asdf=asdf\'
,但到目前为止,我还没有找到一个允许我这样做的单个“挂钩”。这就是我正在寻找的解决方案。如何显式定义给定测试的请求URL。     
已邀请:
        我会做的:
helper.request.stub(:protocol).and_return(\"http://\")
helper.request.stub(:host).and_return(\"www.foo.com\")
helper.request.stub(:port).and_return(80)
helper.request.stub(:port_string).and_return(\":80\")
helper.request.stub(:path).and_return(\"/asdf.asdf\")
helper.canonical_url.should eq(\"http://www.foo.com/asdf.asdf\")
    
        造成这种混乱的最终原因在于ActionPack: ActionDispatch :: TestRequest ActionDispatch :: Http :: URL 例如如果设置端口(ActionDispatch :: TestRequest)
def port=(number)
  @env[\'SERVER_PORT\'] = number.to_i
end
例如然后阅读(ActionDispatch :: Http :: URL)
def raw_host_with_port
  if forwarded = env[\"HTTP_X_FORWARDED_HOST\"]
    forwarded.split(/,\\s?/).last
  else
    env[\'HTTP_HOST\'] || \"#{env[\'SERVER_NAME\'] || env[\'SERVER_ADDR\']}:#{env[\'SERVER_PORT\']}\"
  end
end
仅当您尚未设置SERVER_NAME,HTTP_X_FORWARDED_HOST或HTTP_HOST时,设置SERVER_PORT才会生效。 对于端口设置,我的基本解决方法是将端口添加到主机-因为request.port通常不会执行您想要的操作。 例如设置端口
request.host = \'example.com:1234\'
真正的答案是读取ActionPack中的代码。这很简单。     
        参加这个聚会很晚,但是发现它在搜索类似内容。 怎么样:
allow_any_instance_of(ActionController::TestRequest).to receive(:host).and_return(\'www.fudge.com\')
我很欣赏有时会
allow_any_instance_of
,但这似乎可以完成工作。     

要回复问题请先登录注册