Trace source of deprecation warnings in rails test

2019-02-03 02:02发布

问题:

When running my functional tests, I'm getting the following warning in one of the test cases but I can't pinpoint where it's coming from:

gems/actionpack-2.3.8/lib/action_controller/record_identifier.rb:76: warning: Object#id will be deprecated; use Object#object_id

Unfortunately that's the only line of the backtrace that's shown, even if I run it with rake test --trace, and there is no more information in log/test.log.

How can I get the full backtrace for this warning or otherwise figure out which line in my code is causing it?

回答1:

To solve this you could enable the full debugging information. (see the help)

ActiveSupport::Deprecation.debug = true

As @Eric Anderson says it should be placed after Rails loads (i.e. after require 'rails/all' in application.rb) but before bundler runs to catch deprecation warning in gems (i.e. before Bundler.require(:default, Rails.env) if defined?(Bundler) in application.rb).

You can add a condition, like if ENV["DEBUG"] or if environment == :test to leave this in your config.



回答2:

Had the same issue. A gem was causing a deprecation warning but I had no idea which gem since Rail's message only shows the last bit of the callstack in my code. Add the following:

module ActiveSupport::Deprecation
  class << self
    def deprecation_message_with_debugger(callstack, message = nil)
      debugger
      deprecation_message_without_debugger callstack, message
    end
    alias_method_chain :deprecation_message, :debugger
  end
end

Placed this after Rails loads (i.e. after require 'rails/all' in application.rb) but before bunder runs to catch deprecation warning in gems (i.e. before Bundler.require(:default, Rails.env) if defined?(Bundler) in application.rb).

Now when a deprecation warning is encountered you are dropped in the debugger. You can either leave this in (and surround with a if Rails.env.test?) or remove it when you have found your issues.



回答3:

When I get this kind of warning in my tests it is usually because I am using mocking model objects and am not providing all the methods that active record provides for real.

A good starting point would be the rails code itself. Looking at the source code for the action_pack gem which is referenced, the method that is causing the error is dom_id. That method generates an id for an object for use on a page. It seems to be called in a couple of places internally (unless you are calling it directly of course!) but the most likely cause appears to be calling form_for on an object.