使用rSpec测试机架路由
|
我的route.rb中有一条规则:
constraints AssetRestrictor do
match \'*seopath\' => SeoDispatcher
end
然后在lib / seo_dispatcher.rb中,我有这个:
class SeoDispatcher
AD_KEY = \"action_dispatch.request.path_parameters\"
def self.call(env)
seopath = env[AD_KEY][:seopath]
if seopath
params = seopath.split(\'/\') # get array of path components
env[AD_KEY][:id] = params.last # the real page name is the last element
env[AD_KEY][:category] = params.first if params.length > 1
end
Rails.logger.debug \"routing to show #{env[AD_KEY]}\"
PagesController.action(:show).call(env)
# TODO error handling for invalid paths
end
end
class AssetRestrictor
EXCEPTION_FILES = [\'javascripts\', \'stylesheets\', \'autodiscover\']
def self.matches?(request)
return false if request.method == \'POST\' # no post requests are SEO-ed
EXCEPTION_FILES.each do |ex|
return false if request.url.include?(ex)
end
true
end
end
基本上,整个过程都可以。想法是剥离最后一个路径组件,并将其与页面的块匹配。 SEO人士告诉我,这是诱骗搜索引擎将您排名更高的好方法。
撇开我那刻薄的评论,我在用rSpec编写一个练习该代码的测试时遇到了麻烦。我的第一枪是:
describe SeoDispatcher do
it \"routes /insurance/charters-and-guides/how-to-buy-charter-boat-insurance to pages#show :id => how-to-buy-charter-boat-insurance\" do
{ :get => \"/insurance/charters-and-guides/how-to-buy-charter-boat-insurance\"}.should route_to(
:controller => \'pages\',
:action => \'show\',
:id => \'how-to-buy-charter-boat-insurance\'
)
end
end
但这根本不执行机架分配代码。有谁知道(而不是喜欢它)如何执行代码?我真的很想从Rack中引入参数,而不仅仅是做SeoDispatcher.call({\"action_dispatch.request.path_parameters\" => {:seopath => \"/foo/bar\"}})
。
谢谢!
没有找到相关结果
已邀请:
1 个回复
土投
如果有人知道更好的方法,请随时告诉我!