【发布时间】:2011-06-25 15:54:26
【问题描述】:
我在 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,然后在匹配器中明确设置期望。我希望能够在一个电话中做到这一点,即controller.request.url = 'http://www.foo.com:80/asdf.asdf?asdf=asdf' 或request = ActionController::TestRequest.new :url => 'http://www.foo.com:80/asdf.asdf?asdf=asdf',但到目前为止,我还没有找到一个允许我这样做的“钩子”。这就是我正在寻找的解决方案。 如何明确定义给定测试的请求 URL。
【问题讨论】:
-
PS:我真的不在乎我传入的 URL 是什么。它不需要是应用程序自己的 URL,因为 canonical_url 方法应该适用于任何给定的 URL。但是,我确实想在测试之前明确定义它,而不是依赖于 ActionController::TestRequest 的默认值。
标签: ruby-on-rails unit-testing rspec2 helpers