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

标签 ruby-on-rails-3 testing routes 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

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

最佳答案

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

unless Rails.env.development?

到:

if Rails.env.production?

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

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

相关文章:

ruby-on-rails - 或者,如何使正则表达式动态?

javascript - 配置 Protractor 以忽略浏览器控制台错误

unit-testing - 了解软件测试的工作原理和测试内容

angularjs - Protractor 测试失败,因为添加 ng-if 指令后出现 ElementNotVisibleError

java - 使用 Java 将消息从不同的 IP 地址发送到单个服务器

ruby-on-rails-3 - 从 Rails 中的 url 中删除 "index"

javascript - 如何根据从 Angular 下拉列表中选择的值路由到不同的位置?

ruby-on-rails - Rails 3 Beta 2、Haml、嵌套布局和 LocalJumpError

ruby - 如何扩展 redcarpet 以支持自动链接用户提及?

ruby-on-rails - 如何在 'format.json/xml { render :json/xml => @user.to_json/xml }' 中设置 JSON/XML 响应的 header ?