【问题标题】:How can I use rspec to test routes that are being rescued and redirected?如何使用 rspec 测试正在救援和重定向的路线?
【发布时间】:2011-11-22 16:15:19
【问题描述】:

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

...但是我应该检查什么错误?还是我应该就这样?

【问题讨论】:

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


    【解决方案1】:

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

    unless Rails.env.development?
    

    到:

    if Rails.env.production?
    

    这应该使测试环境脱离您的 rescue404 行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多