ActionDispatch::IntegrationTest 抑制异常

ActionDispatch::IntegrationTest suppresses exceptions

在调试失败的集成测试时,我一直 运行 遇到同样的问题,我的代码中引发的异常被抑制并且没有显示在测试输出中。

例如,对于以下控制器和测试:

class RegistrationController::ApplicationController
  def create
    # some code that raises an exception
  end
end
class RegistrationFlowTest < ActionDispatch::IntegrationTest

  test 'user registers successfully' do
    post sign_up_path, params: { username: 'arnold', password: '123' }
    assert_response :success  
  end

end

输出类似于

Minitest::Assertion: Expected response to be a <2XX: success>, but was a <500: Internal Server Error>

有没有办法查看确切引发的异常?而不仅仅是HTTP响应码的区别?

谢谢!

西蒙

这会发生,因为 Rails 控制器默认处理异常并引发 500 状态,使异常对测试套件不可见(如果在模型的单元测试中引发错误,这非常有帮助)。 here.

讨论了在您的测试套件中禁用此功能的选项或替代解决方法

link 中的关键代码行,应添加到 test/integration/integration_test_helper.rb:

ActionController::Base.class_eval do
  def perform_action
    perform_action_without_rescue
  end
end

Dispatcher.class_eval do
  def self.failsafe_response(output, status, exception = nil)
    raise exception
  end
end

编辑:我注意到 link 现在已经很老了。我真的很熟悉 Rack,所以虽然第一个块对我来说还不错,但我不确定第二个块是否仍然是最新的。如果需要更新,您可能需要查看 the relevant current Rails guide

我推荐的解决这个问题的方法是实际解析 Rails 提供的响应(至少在 testdevelopment 环境中是默认的),其中包括堆栈跟踪错误并在您的测试失败的情况下处理它。这样做的好处是,当出现不会导致测试失败的错误时,它不会输出堆栈跟踪(例如,您有意测试如何处理失败的场景)。

我制作的这个小模块将允许您调用 assert_response_with_errors 断言对调用的响应,但当响应不是您预期的时,以可读格式输出异常消息和堆栈跟踪.

module ActionDispatch
  module Assertions
    module CustomResponseAssertions
      # Use this method when you want to assert a response body but also print the exception
      # and full stack trace to the test console.
      # Useful when you are getting errors in integration tests but don't know what they are.
      #
      # Example:
      # user_session.post create_gene_path, params: {...}
      # user_session.assert_response_with_errors :created
      def assert_response_with_errors(type, message = nil)
        assert_response(type, message)
      rescue Minitest::Assertion => e
        message = e.message
        message += "\nException message: #{@response.parsed_body[:exception]}"
        stack_trace = @response.parsed_body[:traces][:'Application Trace'].map { |line| line[:trace] }.join "\n"
        message += "\nException stack trace start"
        message += "\n#{stack_trace}"
        message += "\nException stack trace end"
        raise Minitest::Assertion, message
      end
    end
  end
end

要使用它,您需要在 Rails 将其堆栈加载到您的 test_helper.rb 之前将其包含到 ActionDispatch::Assertions 中。所以只需将包含添加到您的 test_helper.rb 中,就像这样:

ActionDispatch::Assertions.include ActionDispatch::Assertions::CustomResponseAssertions
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
...