我在routes.rb中设置了一个自定义重定向,它在用户界面上运行良好:
match ':hash' => redirect { |params| begin url = Sharing.find_by_short_url(params[:hash]); "/#{url.shareable_type}/#{url.shareable_id}/" rescue '/' end }, :constraints => { :hash => /[a-zA-Z0-9]{7}/ }
它的作用是获取缩短的URL并查找实际的URL路径。
然而,我的测试失败了:
it "routes GET 'STU1VWX' to stations/1" do
{ :get => "STU1VWX" }.should redirect_to(
:controller => "stations",
:action => "show",
:params => {:id => 1}
)
end
随着:
1) Shorter URL redirect routes GET 'STU1VWX' to stations/1
Failure/Error: { :get => "STU1VWX" }.should route_to(
ActionController::RoutingError:
No route matches "/STU1VWX"
# ./spec/routing_spec.rb:12:in `block (2 levels) in <top (required)>'
所以问题在测试层面被隔离出来。我知道我可以在控制器测试中测试这个问题,但是考虑到代码在routes.rb中,我不应该这样做。在重定向的情况下,使用"should route_to"无法工作的本质原因是什么?
match '/:hash'
代替match ':hash'
吗? - iblue