代码之家  ›  专栏  ›  技术社区  ›  Simon Woodside

在运行功能测试时,如何禁用RubyonRails应用程序中的救援处理程序?

  •  5
  • Simon Woodside  · 技术社区  · 17 年前

    我的RubyonRails应用程序中有许多控制器,在操作结束时有一个救援处理程序,它基本上捕获任何未处理的错误,并返回某种“用户友好”的错误。但是,当我进行rake测试时,我希望禁用那些默认的救援处理程序,以便能够看到完整的错误和堆栈跟踪。有什么自动的方法来做这个吗?

    更新 澄清:我有这样的行动:

    def foo
      # do some stuff...
    rescue
      render :text => "Exception: #{$!}" # this could be any kind of custom render
    end
    

    现在,当我对这个进行功能测试时,如果异常被引发,那么我只会得到一点关于异常的信息,但是我想要的是它的行为就像没有救援处理程序一样,所以我得到了完整的调试信息。

    更新:解决方案

    我这样做了:

      rescue:
        raise unless Rails.env.production?
        render :text => "Exception: #{$!}" # this could be any kind of custom render
      end
    
    5 回复  |  直到 16 年前
        1
  •  9
  •   nioq    16 年前

    不是很自动化,但是如何修改代码以在测试中调用时重新抛出异常?

    也许是这样:

    def foo
      # do some stuff...
    rescue
      raise if ENV["RAILS_ENV"] == "test"
      render :text => "Exception: #{$!}" # this could be any kind of custom render
    end
    
        2
  •  0
  •   Scott    17 年前

    你看过使用 assert_raise( exception1, exception2, ... ) { block } 调用然后从块中打印异常?

        3
  •  0
  •   paxdiablo    17 年前

    你用哪种方法?在ActionController中有两种救援方法。

    我的基本控制器中有这个:

    def rescue_action_in_public(exception)
        response_code = response_code_for_rescue(exception)
        status = interpret_status(response_code)
        respond_to do |format|
            format.html { render_optional_error_file response_code}
            format.js { render :update, :status => status  do |page| page.redirect_to(:url => error_page_url(status)) end}
    end
    

    结束

    这仅在生产模式中显示自定义错误。

        4
  •  0
  •   ndp    17 年前

    我认为最简单的事情是验证是否调用了正确的渲染——或者其他与常规的、非异常的情况不同的情况。

        5
  •  -1
  •   Lucas Wilson-Richter    17 年前

    你不需要关闭你的救援区。使用assert_raise方法(如scott建议的那样),并在块中调用希望从中获得异常的方法。

    例如:

    def test_throws_exception
      assert_raise Exception do
        raise_if_true(true)
      end
    end