如何使用 rspec 来测试正在救援和重定向的路由?
我试图为一个简单的 api 编写一些快速路由测试,所以我写道:
it "delete" do
delete("/api/notifications/:id").should_not be_routable
end
但我收到:
Failure/Error: delete("/api/notifications/:id").should_not be_routable
expected {:delete=>"/api/notifications/:id"} not to be routable, but it routes to {:controller=>"application", :action=>"rescue404", :a=>"api/notifications/:id"}
我很快意识到我正在从 404 中拯救出来,所以几乎所有东西都是可路由的。
unless Rails.env.development?
rescue_from NotFound, :with => :rescue404
rescue_from ActiveRecord::RecordNotFound, :with => :rescue404
rescue_from ActionController::RoutingError, :with => :rescue404
end
def rescue404
respond_to do |format|
format.json { render :text => 'Something went wrong. Record not found or url is incorrect.\n' }
format.xml { render :text => 'Something went wrong. Record not found or url is incorrect.\n' }
format.html { redirect_to root_url, :alert => 'That page does not exist, sorry bro!' }
end
end
这让我需要进行测试:以
it "delete" do
delete("/api/notifications/:id").should route_to("application#rescue404", :a => "api/notifications/:id")
end
这种方式编写对我来说很容易出错,因为我不断得到 ':a =>'错误的。有什么方法可以测试异常是否被拯救?
这有效:
it "delete" do
delete("/api/notifications/:id").should raise_error()
end
...但是我应该检查什么错误?或者我应该就这样留下来吗?
I was trying to write some quick routing tests for a simple api so I wrote:
it "delete" do
delete("/api/notifications/:id").should_not be_routable
end
But I received:
Failure/Error: delete("/api/notifications/:id").should_not be_routable
expected {:delete=>"/api/notifications/:id"} not to be routable, but it routes to {:controller=>"application", :action=>"rescue404", :a=>"api/notifications/:id"}
I quickly realized I was rescuing from 404, so pretty much everything is routable.
unless Rails.env.development?
rescue_from NotFound, :with => :rescue404
rescue_from ActiveRecord::RecordNotFound, :with => :rescue404
rescue_from ActionController::RoutingError, :with => :rescue404
end
def rescue404
respond_to do |format|
format.json { render :text => 'Something went wrong. Record not found or url is incorrect.\n' }
format.xml { render :text => 'Something went wrong. Record not found or url is incorrect.\n' }
format.html { redirect_to root_url, :alert => 'That page does not exist, sorry bro!' }
end
end
That leaves me with this for a test:
it "delete" do
delete("/api/notifications/:id").should route_to("application#rescue404", :a => "api/notifications/:id")
end
Writing this way is error prone to me as I'm constantly getting the ':a =>' wrong. Is there any way I can test if an exception is being rescued?
This works:
it "delete" do
delete("/api/notifications/:id").should raise_error()
end
...but what error should I be checking for? Or should I just leave it at that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以改变你的救援方式。更改
为:
这应该将测试环境排除在你的rescue404行为之外。
You could change your rescues. Change:
to:
That should leave the test env out of your rescue404 behavior.