当我在实践中运行它时它可以工作,但我似乎无法使用rspec为我的路由约束编写一个工作测试.
当测试运行时,触发约束,但请求参数为空,因此它不会验证并且测试失败.
我正在运行Rails 3.0.9,rspec-rails 2.6.1和rspec 2.6.0.
配置/ routes.rb中
match ":param1-unique-:param2" => "controller#index",
:constraints => ParamConstraint.new
LIB / param_constraint.rb
class ParamConstraint
def matches?(request)
@request ||= request
valid_param1? && valid_param2?
end
def valid_param1?
@request.params[:param1] == "lorem"
end
def valid_param2?
@request.params[:param2] == "ipsum"
end
end
规格/路由/ param_constraint_spec.rb
require 'spec_helper'
describe "param constraint routing" do
it "recognizes route for param1 and param2" do
{ :get => "/lorem-unique-ipsum" }.
should route_to(
:controller => "controller",
:action => "index",
:param1 => "lorem",
:param2 => "ipsum"
)
end
end
更新
如果我在约束中检查请求,我得到以下输出:
#<ActionDispatch::Request:0x007fee140ff910 @env={
"rack.version"=>[1, 1],
"rack.input"=>#<StringIO:0x007fee1446da48>,
"rack.errors"=>#<StringIO:0x007fee1446e768>,
"rack.multithread"=>true,
"rack.multiprocess"=>true,
"rack.run_once"=>false,
"REQUEST_METHOD"=>"GET",
"SERVER_NAME"=>"example.org",
"SERVER_PORT"=>"80",
"QUERY_STRING"=>"",
"PATH_INFO"=>"/lorem-unique-ipsum",
"rack.url_scheme"=>"http",
"HTTPS"=>"off",
"SCRIPT_NAME"=>"",
"CONTENT_LENGTH"=>"0"
}>
最佳答案 我今天遇到了同样的问题,正在寻找一个回答我的问题.对于它的价值,我不得不求助于编写请求规范.
context "passing params that satisfy ParamConstraint" do
before do
visit "/lorem-unique-ipsum"
end
it "should serve up a page with content" do
# replace this with some assertion that gets satisfied by
# pages served up when ParamConstraint.new.matches? returns true
page.should have_selector("html body div#foo")
page.should_not have_selector("html body div#bar")
end
end
context "passing params that DO NOT satisfy ParamConstraint" do
before do
visit "/other-unique-other"
end
it "should serve up a page with different content" do
# replace this with some assertion that gets satisfied by
# pages served up when ParamConstraint.new.matches? returns false
page.should_not have_selector("html body div#foo")
page.should have_selector("html body div#bar")
end
end
这不能回答你的问题,我认为这是“如何测试路由约束”,因为正确的方法是通过路由规范.但是考虑到当你使用“should route_to”时request.params的工作方式存在这种差距,这是一种解决方法.与路由规范相反,请求规范将正确填充request.params.