我推荐的解决这个问题的方法是实际解析 Rails 提供的响应(至少默认情况下在test
和development
环境中),其中包括错误的堆栈跟踪,并在测试失败的情况下处理它。这样做的好处是,当出现不会导致测试失败的错误时(例如,您有意测试如何处理失败的场景),它不会输出堆栈跟踪。
我制作的这个小模块将允许您调用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
. 因此,只需将 include 添加到您的test_helper.rb
中,如下所示:
ActionDispatch::Assertions.include ActionDispatch::Assertions::CustomResponseAssertions
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
...