Created
April 23, 2025 20:59
-
-
Save masasakano/e64575c716cdf690d67765f6207f9744 to your computer and use it in GitHub Desktop.
Returns the caller information String in Rails testing; in default it returns the last caller in *_test.rb so it is useful in assertions in library/module files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Returns the String for the caller information | |
# | |
# @example To display the location of the last caller in the *_test.rb file. | |
# assert abc, sprintf("(%s): abc=%s", _get_caller_info_message, abc.inspect) # defined in test_helper.rb | |
# | |
# @example displays the exact line where an error occurs | |
# assert false, _get_caller_info_message(bind_offset: -1, prefix: true)+" Error occurs exactly at this line." | |
# | |
# @param bind_offset: [Integer, NilClass] offset for caller_locations (used for displaying the caller routine). In default (=nil), the last location in *_test.rb (such as, inside a block). If this is 0, it is useful in the case where this method is called in a test library method that is called from an original test routine. Therefore, specify "-1" to get the information of the caller itself (Second example above). | |
# @param fmt: [String] sprintf format. It must contain %s (for path) and %d (or %s) (for line number) in this order. | |
# @param prefix: [Boolean] If true (Def: false), the return is enclosed with a pair of parentheses, followed by a colon | |
# @return [String] | |
def get_caller_info_message(bind_offset: nil, fmt: "%s:%d", prefix: false) | |
if !bind_offset | |
bind = caller_locations.each{|i| break i if /_test\.rb$/ =~ i.absolute_path } | |
if bind.respond_to? :absolute_path | |
bind_offset = nil | |
else | |
bind = nil | |
bind_offset = 0 # in failure (meaning when this method is NOT called from a Rails test file) | |
end | |
end | |
bind ||= caller_locations(2+bind_offset, 1)[0] # Ruby 2.0+ | |
# NOTE: bind.label returns "block in <class:TranslationIntegrationTest>" | |
ret = sprintf fmt, bind.absolute_path.sub(%r@.*(/test/)@, '\1'), bind.lineno | |
(prefix ? sprintf("(%s):", ret) : ret) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment