gpt4 book ai didi

ruby-on-rails-3 - 我如何使用 rspec 来测试正在救援和重定向的路由?

转载 作者:行者123 更新时间:2023-11-28 20:57:41 24 4
gpt4 key购买 nike

我试图为一个简单的 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

...但是我应该检查什么错误?还是我应该就此打住?

最佳答案

你可以改变你的救援。变化:

unless Rails.env.development?

到:

if Rails.env.production?

这应该将测试环境排除在您的 rescue404 行为之外。

关于ruby-on-rails-3 - 我如何使用 rspec 来测试正在救援和重定向的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8229971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com