You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

invoke_in_world.rb 2.4 kB

2 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # frozen_string_literal: true
  2. require 'cucumber/platform'
  3. module Cucumber
  4. module Glue
  5. # Utility methods for executing step definitions with nice backtraces etc.
  6. # TODO: add unit tests
  7. # TODO: refactor for readability
  8. class InvokeInWorld
  9. def self.replace_instance_exec_invocation_line!(backtrace, instance_exec_invocation_line, pseudo_method)
  10. return if Cucumber.use_full_backtrace
  11. instance_exec_pos = backtrace.index(instance_exec_invocation_line)
  12. return unless instance_exec_pos
  13. replacement_line = instance_exec_pos + INSTANCE_EXEC_OFFSET
  14. backtrace[replacement_line].gsub!(/`.*'/, "`#{pseudo_method}'") if pseudo_method
  15. depth = backtrace.count { |line| line == instance_exec_invocation_line }
  16. end_pos = depth > 1 ? instance_exec_pos : -1
  17. backtrace[replacement_line + 1..end_pos] = nil
  18. backtrace.compact!
  19. end
  20. def self.cucumber_instance_exec_in(world, check_arity, pseudo_method, *args, &block)
  21. cucumber_run_with_backtrace_filtering(pseudo_method) do
  22. if check_arity && !cucumber_compatible_arity?(args, block)
  23. world.instance_exec do
  24. ari = block.arity
  25. ari = ari < 0 ? "#{ari.abs - 1}+" : ari
  26. s1 = ari == 1 ? '' : 's'
  27. s2 = args.length == 1 ? '' : 's'
  28. raise ArityMismatchError, "Your block takes #{ari} argument#{s1}, but the Regexp matched #{args.length} argument#{s2}."
  29. end
  30. else
  31. world.instance_exec(*args, &block)
  32. end
  33. end
  34. end
  35. def self.cucumber_compatible_arity?(args, block)
  36. return true if block.arity == args.length
  37. return true if block.arity.negative? && args.length >= (block.arity.abs - 1)
  38. false
  39. end
  40. def self.cucumber_run_with_backtrace_filtering(pseudo_method)
  41. yield
  42. rescue Exception => e # rubocop:disable Lint/RescueException
  43. instance_exec_invocation_line = "#{__FILE__}:#{__LINE__ - 2}:in `cucumber_run_with_backtrace_filtering'"
  44. replace_instance_exec_invocation_line!((e.backtrace || []), instance_exec_invocation_line, pseudo_method)
  45. raise e
  46. end
  47. INSTANCE_EXEC_OFFSET = -3
  48. end
  49. # Raised if the number of a StepDefinition's Regexp match groups
  50. # is different from the number of Proc arguments.
  51. class ArityMismatchError < StandardError
  52. end
  53. end
  54. end

No Description

Contributors (1)