如何使用rspec测试正在获救和重定向的路由?

时间:2011-11-22 16:15:19

标签: ruby-on-rails-3 testing routing bdd rspec-rails

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

...但我应该检查什么错误?或者我应该把它留在那?

1 个答案:

答案 0 :(得分:0)

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

unless Rails.env.development?

为:

if Rails.env.production?

这应该让测试环境脱离你的救援行为。