Chr*_*oom 3 unit-testing ruby-on-rails helpers rspec2
我有一个在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
Run Code Online (Sandbox Code Playgroud)
编辑:
最后,我想测试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.
我做过:
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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4875 次 |
| 最近记录: |