<NME> configuration.rb <BEF> RSpec::Support.require_rspec_core "backtrace_formatter" RSpec::Support.require_rspec_core "ruby_project" RSpec::Support.require_rspec_core "formatters/deprecation_formatter" RSpec::Support.require_rspec_core "output_wrapper" module RSpec module Core # rubocop:disable Metrics/ClassLength # Stores runtime configuration information. # # Configuration options are loaded from multiple files and joined together # with command-line switches and the `SPEC_OPTS` environment variable. # # Precedence order (where later entries overwrite earlier entries on # conflicts): # # * Global (`$XDG_CONFIG_HOME/rspec/options`, or `~/.rspec` if it does # not exist) # * Project-specific (`./.rspec`) # * Local (`./.rspec-local`) # * Command-line options # * `SPEC_OPTS` # # For example, an option set in the local file will override an option set # in your global file. # # The global, project-specific and local files can all be overridden with a # separate custom file using the --options command-line parameter. # # @example Standard settings # RSpec.configure do |c| # c.drb = true # c.drb_port = 1234 # c.default_path = 'behavior' # end # # @example Hooks # RSpec.configure do |c| # c.before(:suite) { establish_connection } # c.before(:example) { log_in_as :authorized } # c.around(:example) { |ex| Database.transaction(&ex) } # end # # @see RSpec.configure # @see Hooks class Configuration include RSpec::Core::Hooks # Module that holds `attr_reader` declarations. It's in a separate # module to allow us to override those methods and use `super`. # @private Readers = Module.new include Readers # @private class MustBeConfiguredBeforeExampleGroupsError < StandardError; end # @private def self.define_reader(name) Readers.class_eval do remove_method name if method_defined?(name) attr_reader name end define_method(name) { value_for(name) { super() } } end # @private def self.define_alias(name, alias_name) alias_method alias_name, name alias_method "#{alias_name}=", "#{name}=" define_predicate alias_name end # @private def self.define_predicate(name) define_method "#{name}?" do !!send(name) end end # @private # # Invoked by the `add_setting` instance method. Use that method on a # `Configuration` instance rather than this class method. def self.add_setting(name, opts={}) raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default) attr_writer name add_read_only_setting name Array(opts[:alias_with]).each do |alias_name| define_alias(name, alias_name) end end # @private # # As `add_setting` but only add the reader. def self.add_read_only_setting(name, opts={}) raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default) define_reader name define_predicate name end # @macro [attach] add_setting # @!attribute [rw] $1 # # @macro [attach] define_reader # @!attribute [r] $1 # @macro add_setting # Path to use if no path is provided to the `rspec` command (default: # `"spec"`). Allows you to just type `rspec` instead of `rspec spec` to # run all the examples in the `spec` directory. # # @note Other scripts invoking `rspec` indirectly will ignore this # setting. # @return [String] add_read_only_setting :default_path def default_path=(path) project_source_dirs << path @default_path = path end # @macro add_setting # Run examples over DRb (default: `false`). RSpec doesn't supply the DRb # server, but you can use tools like spork. # @return [Boolean] add_setting :drb # @macro add_setting # The drb_port (default: nil). add_setting :drb_port # @macro add_setting # Default: `$stderr`. add_setting :error_stream # Indicates if the DSL has been exposed off of modules and `main`. # Default: true # @return [Boolean] def expose_dsl_globally? Core::DSL.exposed_globally? end # Use this to expose the core RSpec DSL via `Module` and the `main` # object. It will be set automatically but you can override it to # remove the DSL. # Default: true def expose_dsl_globally=(value) if value Core::DSL.expose_globally! Core::SharedExampleGroup::TopLevelDSL.expose_globally! else Core::DSL.remove_globally! Core::SharedExampleGroup::TopLevelDSL.remove_globally! end end # Determines where deprecation warnings are printed. # Defaults to `$stderr`. # @return [IO, String] IO or filename to write to define_reader :deprecation_stream # Determines where deprecation warnings are printed. # @param value [IO, String] IO to write to or filename to write to def deprecation_stream=(value) if @reporter && !value.equal?(@deprecation_stream) warn "RSpec's reporter has already been initialized with " \ "#{deprecation_stream.inspect} as the deprecation stream, so your change to "\ "`deprecation_stream` will be ignored. You should configure it earlier for " \ "it to take effect, or use the `--deprecation-out` CLI option. " \ "(Called from #{CallerFilter.first_non_rspec_line})" else @deprecation_stream = value end end # @macro define_reader # The file path to use for persisting example statuses. Necessary for the # `--only-failures` and `--next-failure` CLI options. # # @overload example_status_persistence_file_path # @return [String] the file path # @overload example_status_persistence_file_path=(value) # @param value [String] the file path define_reader :example_status_persistence_file_path # Sets the file path to use for persisting example statuses. Necessary for the # `--only-failures` and `--next-failure` CLI options. def example_status_persistence_file_path=(value) @example_status_persistence_file_path = value clear_values_derived_from_example_status_persistence_file_path end # @macro define_reader # Indicates if the `--only-failures` (or `--next-failure`) flag is being used. define_reader :only_failures alias_method :only_failures?, :only_failures # @private def only_failures_but_not_configured? only_failures? && !example_status_persistence_file_path end # @macro define_reader # If specified, indicates the number of failures required before cleaning # up and exit (default: `nil`). Can also be `true` to fail and exit on first # failure define_reader :fail_fast # @see fail_fast def fail_fast=(value) case value when true, 'true' @fail_fast = true when false, 'false', 0 @fail_fast = false when nil @fail_fast = nil else @fail_fast = value.to_i if value.to_i == 0 # TODO: in RSpec 4, consider raising an error here. RSpec.warning "Cannot set `RSpec.configuration.fail_fast`" \ " to `#{value.inspect}`. Only `true`, `false`, `nil` and integers" \ " are valid values." @fail_fast = true end end end # @macro add_setting # Prints the formatter output of your suite without running any # examples or hooks. add_setting :dry_run # @macro add_setting # The exit code to return if there are any failures (default: 1). # @return [Integer] add_setting :failure_exit_code # @macro add_setting # The exit code to return if there are any errors outside examples (default: failure_exit_code) # @return [Integer] add_setting :error_exit_code # @macro add_setting # Whether or not to fail when there are no RSpec examples (default: false). # @return [Boolean] add_setting :fail_if_no_examples # @macro define_reader # Indicates files configured to be required. # @return [Array<String>] define_reader :requires # @macro define_reader # Returns dirs that have been prepended to the load path by the `-I` # command line option. # @return [Array<String>] define_reader :libs # @macro add_setting # Determines where RSpec will send its output. # Default: `$stdout`. # @return [IO, String] define_reader :output_stream # Set the output stream for reporter. # @attr value [IO, String] IO to write to or filename to write to, defaults to $stdout def output_stream=(value) if @reporter && !value.equal?(@output_stream) warn "RSpec's reporter has already been initialized with " \ "#{output_stream.inspect} as the output stream, so your change to "\ "`output_stream` will be ignored. You should configure it earlier for " \ "it to take effect. (Called from #{CallerFilter.first_non_rspec_line})" else @output_stream = value output_wrapper.output = @output_stream end end # @macro define_reader # Load files matching this pattern (default: `'**{,/*/**}/*_spec.rb'`). # @return [String] define_reader :pattern # Set pattern to match files to load. # @attr value [String] the filename pattern to filter spec files by def pattern=(value) update_pattern_attr :pattern, value end # @macro define_reader # Exclude files matching this pattern. # @return [String] define_reader :exclude_pattern # Set pattern to match files to exclude. # @attr value [String] the filename pattern to exclude spec files by def exclude_pattern=(value) update_pattern_attr :exclude_pattern, value end # @macro add_setting # Specifies which directories contain the source code for your project. # When a failure occurs, RSpec looks through the backtrace to find a # a line of source to print. It first looks for a line coming from # one of the project source directories so that, for example, it prints # the expectation or assertion call rather than the source code from # the expectation or assertion framework. # @return [Array<String>] add_setting :project_source_dirs # @macro add_setting # Report the times for the slowest examples (default: `false`). # Use this to specify the number of examples to include in the profile. # @return [Boolean] attr_writer :profile_examples define_predicate :profile_examples # @macro add_setting # Run all examples if none match the configured filters # (default: `false`). # @deprecated Use {#filter_run_when_matching} instead for the specific # filters that you want to be ignored if none match. add_setting :run_all_when_everything_filtered # @macro add_setting # Color to use to indicate success. Defaults to `:green` but can be set # to one of the following: `[:black, :white, :red, :green, :yellow, # :blue, :magenta, :cyan]` # @return [Symbol] add_setting :success_color # @macro add_setting # Color to use to print pending examples. Defaults to `:yellow` but can # be set to one of the following: `[:black, :white, :red, :green, # :yellow, :blue, :magenta, :cyan]` # @return [Symbol] add_setting :pending_color # @macro add_setting # Color to use to indicate failure. Defaults to `:red` but can be set to # one of the following: `[:black, :white, :red, :green, :yellow, :blue, # :magenta, :cyan]` # @return [Symbol] add_setting :failure_color # @macro add_setting # The default output color. Defaults to `:white` but can be set to one of # the following: `[:black, :white, :red, :green, :yellow, :blue, # :magenta, :cyan]` # @return [Symbol] add_setting :default_color # @macro add_setting # Color used when a pending example is fixed. Defaults to `:blue` but can # be set to one of the following: `[:black, :white, :red, :green, # :yellow, :blue, :magenta, :cyan]` # @return [Symbol] add_setting :fixed_color # @macro add_setting # Color used to print details. Defaults to `:cyan` but can be set to one # of the following: `[:black, :white, :red, :green, :yellow, :blue, # :magenta, :cyan]` # @return [Symbol] add_setting :detail_color # @macro add_setting # Don't print filter info i.e. "Run options: include {:focus=>true}" # (default `false`). # return [Boolean] add_setting :silence_filter_announcements # @deprecated This config option was added in RSpec 2 to pave the way # for this being the default behavior in RSpec 3. Now this option is # a no-op. def treat_symbols_as_metadata_keys_with_true_values=(_value) RSpec.deprecate( "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=", :message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " \ "is deprecated, it is now set to true as default and " \ "setting it to false has no effect." ) end # @macro define_reader # Configures how RSpec treats metadata passed as part of a shared example # group definition. For example, given this shared example group definition: # # RSpec.shared_context "uses DB", :db => true do # around(:example) do |ex| # MyORM.transaction(:rollback => true, &ex) # end # end # # ...there are two ways RSpec can treat the `:db => true` metadata, each # of which has a corresponding config option: # # 1. `:trigger_inclusion`: this shared context will be implicitly included # in any groups (or examples) that have `:db => true` metadata. # 2. `:apply_to_host_groups`: the metadata will be inherited by the metadata # hash of all host groups and examples. # # `:trigger_inclusion` is the legacy behavior from before RSpec 3.5 but should # be considered deprecated. Instead, you can explicitly include a group with # `include_context`: # # RSpec.describe "My model" do # include_context "uses DB" # end # # ...or you can configure RSpec to include the context based on matching metadata # using an API that mirrors configured module inclusion: # # RSpec.configure do |rspec| # rspec.include_context "uses DB", :db => true # end # # `:apply_to_host_groups` is a new feature of RSpec 3.5 and will be the only # supported behavior in RSpec 4. # # @overload shared_context_metadata_behavior # @return [:trigger_inclusion, :apply_to_host_groups] the configured behavior # @overload shared_context_metadata_behavior=(value) # @param value [:trigger_inclusion, :apply_to_host_groups] sets the configured behavior define_reader :shared_context_metadata_behavior # @see shared_context_metadata_behavior def shared_context_metadata_behavior=(value) case value when :trigger_inclusion, :apply_to_host_groups @shared_context_metadata_behavior = value else raise ArgumentError, "Cannot set `RSpec.configuration." \ "shared_context_metadata_behavior` to `#{value.inspect}`. Only " \ "`:trigger_inclusion` and `:apply_to_host_groups` are valid values." end end # Record the start time of the spec suite to measure load time. # return [Time] add_setting :start_time # @macro add_setting # Use threadsafe options where available. # Currently this will place a mutex around memoized values such as let blocks. # return [Boolean] add_setting :threadsafe # @macro add_setting # Maximum count of failed source lines to display in the failure reports. # (default `10`). # return [Integer] add_setting :max_displayed_failure_line_count # Determines which bisect runner implementation gets used to run subsets # of the suite during a bisection. Your choices are: # # - `:shell`: Performs a spec run by shelling out, booting RSpec and your # application environment each time. This runner is the most widely # compatible runner, but is not as fast. On platforms that do not # support forking, this is the default. # - `:fork`: Pre-boots RSpec and your application environment in a parent # process, and then forks a child process for each spec run. This runner # tends to be significantly faster than the `:shell` runner but cannot # be used in some situations. On platforms that support forking, this # is the default. If you use this runner, you should ensure that all # of your one-time setup logic goes in a `before(:suite)` hook instead # of getting run at the top-level of a file loaded by `--require`. # # @note This option will only be used by `--bisect` if you set it in a file # loaded via `--require`. # # @return [Symbol] attr_reader :bisect_runner def bisect_runner=(value) if @bisect_runner_class && value != @bisect_runner raise "`config.bisect_runner = #{value.inspect}` can no longer take " \ "effect as the #{@bisect_runner.inspect} bisect runnner is already " \ "in use. This config setting must be set in a file loaded by a " \ "`--require` option (passed at the CLI or in a `.rspec` file) for " \ "it to have any effect." end @bisect_runner = value end # @private # @deprecated Use {#color_mode} = :on, instead of {#color} with {#tty} add_setting :tty # @private attr_writer :files_to_run # @private attr_accessor :filter_manager, :world # @private attr_accessor :static_config_filter_manager # @private attr_reader :backtrace_formatter, :ordering_manager, :loaded_spec_files # rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/MethodLength # Build an object to store runtime configuration options and set defaults def initialize # rubocop:disable Style/GlobalVars @start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now # rubocop:enable Style/GlobalVars @expectation_frameworks = [] @include_modules = FilterableItemRepository::QueryOptimized.new(:any?) @extend_modules = FilterableItemRepository::QueryOptimized.new(:any?) @prepend_modules = FilterableItemRepository::QueryOptimized.new(:any?) @bisect_runner = RSpec::Support::RubyFeatures.fork_supported? ? :fork : :shell @bisect_runner_class = nil @before_suite_hooks = [] @after_suite_hooks = [] @mock_framework = nil @files_or_directories_to_run = [] @loaded_spec_files = Set.new @color = false @color_mode = :automatic @pattern = '**{,/*/**}/*_spec.rb' @exclude_pattern = '' @failure_exit_code = 1 @error_exit_code = nil # so it can be overridden by failure exit code @fail_if_no_examples = false @spec_files_loaded = false @backtrace_formatter = BacktraceFormatter.new @default_path = 'spec' @project_source_dirs = %w[ spec lib app ] @deprecation_stream = $stderr @output_stream = $stdout @reporter = nil @reporter_buffer = nil @filter_manager = FilterManager.new @static_config_filter_manager = FilterManager.new @ordering_manager = Ordering::ConfigurationManager.new @preferred_options = {} @failure_color = :red @success_color = :green @pending_color = :yellow @default_color = :white @fixed_color = :blue @detail_color = :cyan @profile_examples = false @requires = [] @libs = [] @derived_metadata_blocks = FilterableItemRepository::QueryOptimized.new(:any?) @threadsafe = true @max_displayed_failure_line_count = 10 @world = World::Null @shared_context_metadata_behavior = :trigger_inclusion define_built_in_hooks end # rubocop:enable Metrics/AbcSize # rubocop:enable Metrics/MethodLength # @private # # Used to set higher priority option values from the command line. def force(hash) ordering_manager.force(hash) @preferred_options.merge!(hash) return unless hash.key?(:example_status_persistence_file_path) clear_values_derived_from_example_status_persistence_file_path end # @private def reset @spec_files_loaded = false reset_reporter end # @private def reset_reporter @reporter = nil @formatter_loader = nil @output_wrapper = nil end # @private def reset_filters self.filter_manager = FilterManager.new filter_manager.include_only( Metadata.deep_hash_dup(static_config_filter_manager.inclusions.rules) ) filter_manager.exclude_only( Metadata.deep_hash_dup(static_config_filter_manager.exclusions.rules) ) end # @overload add_setting(name) # @overload add_setting(name, opts) # @option opts [Symbol] :default # # Set a default value for the generated getter and predicate methods: # # add_setting(:foo, :default => "default value") # # @option opts [Symbol] :alias_with # # Use `:alias_with` to alias the setter, getter, and predicate to # another name, or names: # # add_setting(:foo, :alias_with => :bar) # add_setting(:foo, :alias_with => [:bar, :baz]) # # Adds a custom setting to the RSpec.configuration object. # # RSpec.configuration.add_setting :foo # # Used internally and by extension frameworks like rspec-rails, so they # can add config settings that are domain specific. For example: # # RSpec.configure do |c| # c.add_setting :use_transactional_fixtures, # :default => true, # :alias_with => :use_transactional_examples # end # # `add_setting` creates three methods on the configuration object, a # setter, a getter, and a predicate: # # RSpec.configuration.foo=(value) # RSpec.configuration.foo # RSpec.configuration.foo? # Returns true if foo returns anything but nil or false. def add_setting(name, opts={}) default = opts.delete(:default) (class << self; self; end).class_exec do add_setting(name, opts) end __send__("#{name}=", default) if default end # Returns the configured mock framework adapter module. # @return [Symbol] def mock_framework if @mock_framework.nil? begin mock_with :rspec rescue LoadError mock_with :nothing end end @mock_framework end # Delegates to mock_framework=(framework). def mock_framework=(framework) mock_with framework end # Regexps used to exclude lines from backtraces. # # Excludes lines from ruby (and jruby) source, installed gems, anything # in any "bin" directory, and any of the RSpec libs (outside gem # installs) by default. # # You can modify the list via the getter, or replace it with the setter. # # To override this behaviour and display a full backtrace, use # `--backtrace` on the command line, in a `.rspec` file, or in the # `rspec_options` attribute of RSpec's rake task. # @return [Array<Regexp>] def backtrace_exclusion_patterns @backtrace_formatter.exclusion_patterns end # Set regular expressions used to exclude lines in backtrace. # @param patterns [Array<Regexp>] set backtrace_formatter exlusion_patterns def backtrace_exclusion_patterns=(patterns) @backtrace_formatter.exclusion_patterns = patterns end # Regexps used to include lines in backtraces. # # Defaults to [Regexp.new Dir.getwd]. # # Lines that match an exclusion _and_ an inclusion pattern # will be included. # # You can modify the list via the getter, or replace it with the setter. # @return [Array<Regexp>] def backtrace_inclusion_patterns @backtrace_formatter.inclusion_patterns end # Set regular expressions used to include lines in backtrace. # @attr patterns [Array<Regexp>] set backtrace_formatter inclusion_patterns def backtrace_inclusion_patterns=(patterns) @backtrace_formatter.inclusion_patterns = patterns end # Adds {#backtrace_exclusion_patterns} that will filter lines from # the named gems from backtraces. # # @param gem_names [Array<String>] Names of the gems to filter # # @example # RSpec.configure do |config| # config.filter_gems_from_backtrace "rack", "rake" # end # # @note The patterns this adds will match the named gems in their common # locations (e.g. system gems, vendored with bundler, installed as a # :git dependency with bundler, etc) but is not guaranteed to work for # all possible gem locations. For example, if you have the gem source # in a directory with a completely unrelated name, and use bundler's # :path option, this will not filter it. def filter_gems_from_backtrace(*gem_names) gem_names.each do |name| @backtrace_formatter.filter_gem(name) end end # @private MOCKING_ADAPTERS = { :rspec => :RSpec, :flexmock => :Flexmock, :rr => :RR, :mocha => :Mocha, :nothing => :Null } # Sets the mock framework adapter module. # # `framework` can be a Symbol or a Module. # # Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the # named framework. # # Given `:nothing`, configures no framework. Use this if you don't use # any mocking framework to save a little bit of overhead. # # Given a Module, includes that module in every example group. The module # should adhere to RSpec's mock framework adapter API: # # setup_mocks_for_rspec # - called before each example # # verify_mocks_for_rspec # - called after each example if the example hasn't yet failed. # Framework should raise an exception when expectations fail # # teardown_mocks_for_rspec # - called after verify_mocks_for_rspec (even if there are errors) # # If the module responds to `configuration` and `mock_with` receives a # block, it will yield the configuration object to the block e.g. # # config.mock_with OtherMockFrameworkAdapter do |mod_config| # mod_config.custom_setting = true # end def mock_with(framework) framework_module = if framework.is_a?(Module) framework else const_name = MOCKING_ADAPTERS.fetch(framework) do raise ArgumentError, "Unknown mocking framework: #{framework.inspect}. " \ "Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}" end RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}" RSpec::Core::MockingAdapters.const_get(const_name) end new_name, old_name = [framework_module, @mock_framework].map do |mod| mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed end unless new_name == old_name assert_no_example_groups_defined(:mock_framework) end if block_given? raise "#{framework_module} must respond to `configuration` so that " \ "mock_with can yield it." unless framework_module.respond_to?(:configuration) yield framework_module.configuration end @mock_framework = framework_module end # Returns the configured expectation framework adapter module(s) def expectation_frameworks if @expectation_frameworks.empty? begin expect_with :rspec rescue LoadError expect_with Module.new end end @expectation_frameworks end # Delegates to expect_with(framework). def expectation_framework=(framework) expect_with(framework) end # Sets the expectation framework module(s) to be included in each example # group. # # `frameworks` can be `:rspec`, `:test_unit`, `:minitest`, a custom # module, or any combination thereof: # # config.expect_with :rspec # config.expect_with :test_unit # config.expect_with :minitest # config.expect_with :rspec, :minitest # config.expect_with OtherExpectationFramework # # RSpec will translate `:rspec`, `:minitest`, and `:test_unit` into the # appropriate modules. # # ## Configuration # # If the module responds to `configuration`, `expect_with` will # yield the `configuration` object if given a block: # # config.expect_with OtherExpectationFramework do |custom_config| # custom_config.custom_setting = true # end def expect_with(*frameworks) modules = frameworks.map do |framework| case framework when Module framework when :rspec require 'rspec/expectations' # Tag this exception class so our exception formatting logic knows # that it satisfies the `MultipleExceptionError` interface. ::RSpec::Expectations::MultipleExpectationsNotMetError.__send__( :include, MultipleExceptionError::InterfaceTag ) ::RSpec::Matchers when :test_unit require 'rspec/core/test_unit_assertions_adapter' ::RSpec::Core::TestUnitAssertionsAdapter when :minitest require 'rspec/core/minitest_assertions_adapter' ::RSpec::Core::MinitestAssertionsAdapter else raise ArgumentError, "#{framework.inspect} is not supported" end end if (modules - @expectation_frameworks).any? assert_no_example_groups_defined(:expect_with) end if block_given? raise "expect_with only accepts a block with a single argument. " \ "Call expect_with #{modules.length} times, " \ "once with each argument, instead." if modules.length > 1 raise "#{modules.first} must respond to `configuration` so that " \ "expect_with can yield it." unless modules.first.respond_to?(:configuration) yield modules.first.configuration end @expectation_frameworks.push(*modules) end # Check if full backtrace is enabled. # @return [Boolean] is full backtrace enabled def full_backtrace? @backtrace_formatter.full_backtrace? end # Toggle full backtrace. # @attr true_or_false [Boolean] toggle full backtrace display def full_backtrace=(true_or_false) @backtrace_formatter.full_backtrace = true_or_false end # Enables color output if the output is a TTY. As of RSpec 3.6, this is # the default behavior and this option is retained only for backwards # compatibility. # # @deprecated No longer recommended because of complex behavior. Instead, # rely on the fact that TTYs will display color by default, or set # {#color_mode} to :on to display color on a non-TTY output. # @see color_mode # @see color_enabled? # @return [Boolean] def color value_for(:color) { @color } end # The mode for determining whether to display output in color. One of: # # - :automatic - the output will be in color if the output is a TTY (the # default) # - :on - the output will be in color, whether or not the output is a TTY # - :off - the output will not be in color # # @see color_enabled? # @return [Boolean] def color_mode value_for(:color_mode) { @color_mode } end # Check if color is enabled for a particular output. # @param output [IO] an output stream to use, defaults to the current # `output_stream` # @return [Boolean] def color_enabled?(output=output_stream) case color_mode when :on then true when :off then false else # automatic output_to_tty?(output) || (color && tty?) end end # Set the color mode. attr_writer :color_mode # Toggle output color. # # @deprecated No longer recommended because of complex behavior. Instead, # rely on the fact that TTYs will display color by default, or set # {:color_mode} to :on to display color on a non-TTY output. attr_writer :color # @private def libs=(libs) libs.map do |lib| @libs.unshift lib $LOAD_PATH.unshift lib end end # Run examples matching on `description` in all files to run. # @param description [String, Regexp] the pattern to filter on def full_description=(description) filter_run :full_description => Regexp.union(*Array(description).map { |d| Regexp.new(d) }) end # @return [Array] full description filter def full_description filter.fetch :full_description, nil end # @overload add_formatter(formatter) # @overload add_formatter(formatter, output) # # @param formatter [Class, String, Object] formatter to use. Can be any of the # string values supported from the CLI (`p`/`progress`, # `d`/`doc`/`documentation`, `h`/`html`, or `j`/`json`), any # class that implements the formatter protocol and has registered # itself with RSpec as a formatter, or a formatter instance. # @param output [String, IO] where the formatter will write its output. # Can be an IO object or a string path to a file. If not provided, # the configured `output_stream` (`$stdout`, by default) will be used. # # Adds a formatter to the set RSpec will use for this run. # # @see RSpec::Core::Formatters::Protocol def add_formatter(formatter, output=output_wrapper) formatter_loader.add(formatter, output) end alias_method :formatter=, :add_formatter # The formatter that will be used if no formatter has been set. # Defaults to 'progress'. def default_formatter formatter_loader.default_formatter end # Sets a fallback formatter to use if none other has been set. # # @example # # RSpec.configure do |rspec| # rspec.default_formatter = 'doc' # end def default_formatter=(value) formatter_loader.default_formatter = value end # Returns a duplicate of the formatters currently loaded in # the `FormatterLoader` for introspection. # # Note as this is a duplicate, any mutations will be disregarded. # # @return [Array] the formatters currently loaded def formatters formatter_loader.formatters.dup end # @private def formatter_loader @formatter_loader ||= Formatters::Loader.new(Reporter.new(self)) end # @private # # This buffer is used to capture all messages sent to the reporter during # reporter initialization. It can then replay those messages after the # formatter is correctly initialized. Otherwise, deprecation warnings # during formatter initialization can cause an infinite loop. class DeprecationReporterBuffer def initialize @calls = [] end def deprecation(*args) @calls << args end def play_onto(reporter) @calls.each do |args| reporter.deprecation(*args) end formatter_ref elsif string_const?(formatter_ref) begin formatter_ref.scan(/(?:::|^)(\w+)/).flatten.inject(Object) { |const,string| const.const_get string } rescue NameError require( path_for(formatter_ref) ) ? retry : raise end @reporter_buffer || @reporter ||= begin @reporter_buffer = DeprecationReporterBuffer.new formatter_loader.prepare_default output_wrapper, deprecation_stream @reporter_buffer.play_onto(formatter_loader.reporter) @reporter_buffer = nil formatter_loader.reporter end end # @api private # # Defaults `profile_examples` to 10 examples when `@profile_examples` is # `true`. def profile_examples profile = value_for(:profile_examples) { @profile_examples } if profile && !profile.is_a?(Integer) 10 else profile end end # @private def files_or_directories_to_run=(*files) files = files.flatten if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty? files << default_path end @files_or_directories_to_run = files @files_to_run = nil end # The spec files RSpec will run. # @return [Array] specified files about to run def files_to_run @files_to_run ||= get_files_to_run(@files_or_directories_to_run) end # @private def last_run_statuses @last_run_statuses ||= Hash.new(UNKNOWN_STATUS).tap do |statuses| if (path = example_status_persistence_file_path) begin ExampleStatusPersister.load_from(path).inject(statuses) do |hash, example| status = example[:status] status = UNKNOWN_STATUS unless VALID_STATUSES.include?(status) hash[example.fetch(:example_id)] = status hash end rescue SystemCallError => e RSpec.warning "Could not read from #{path.inspect} (configured as " \ "`config.example_status_persistence_file_path`) due " \ "to a system error: #{e.inspect}. Please check that " \ "the config option is set to an accessible, valid " \ "file path", :call_site => nil end end end end # @private UNKNOWN_STATUS = "unknown".freeze # @private FAILED_STATUS = "failed".freeze # @private PASSED_STATUS = "passed".freeze # @private PENDING_STATUS = "pending".freeze # @private VALID_STATUSES = [UNKNOWN_STATUS, FAILED_STATUS, PASSED_STATUS, PENDING_STATUS] # @private def spec_files_with_failures @spec_files_with_failures ||= last_run_statuses.inject(Set.new) do |files, (id, status)| files << Example.parse_id(id).first if status == FAILED_STATUS files end.to_a end # Creates a method that delegates to `example` including the submitted # `args`. Used internally to add variants of `example` like `pending`: # @param name [String] example name alias # @param args [Array<Symbol>, Hash] metadata for the generated example # # @note The specific example alias below (`pending`) is already # defined for you. # @note Use with caution. This extends the language used in your # specs, but does not add any additional documentation. We use this # in RSpec to define methods like `focus` and `xit`, but we also add # docs for those methods. # # @example # RSpec.configure do |config| # config.alias_example_to :pending, :pending => true # end # # # This lets you do this: # # RSpec.describe Thing do # pending "does something" do # thing = Thing.new # end # end # # # ... which is the equivalent of # # RSpec.describe Thing do # it "does something", :pending => true do # thing = Thing.new # end # end def alias_example_to(name, *args) extra_options = Metadata.build_hash_from(args) RSpec::Core::ExampleGroup.define_example_method(name, extra_options) end # Creates a method that defines an example group with the provided # metadata. Can be used to define example group/metadata shortcuts. # # @example # RSpec.configure do |config| # config.alias_example_group_to :describe_model, :type => :model # end # # shared_context_for "model tests", :type => :model do # # define common model test helper methods, `let` declarations, etc # end # # # This lets you do this: # # RSpec.describe_model User do # end # # # ... which is the equivalent of # # RSpec.describe User, :type => :model do # end # # @note The defined aliased will also be added to the top level # (e.g. `main` and from within modules) if # `expose_dsl_globally` is set to true. # @see #alias_example_to # @see #expose_dsl_globally= def alias_example_group_to(new_name, *args) extra_options = Metadata.build_hash_from(args) RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options) end # Define an alias for it_should_behave_like that allows different # language (like "it_has_behavior" or "it_behaves_like") to be # employed when including shared examples. # # @example # RSpec.configure do |config| # config.alias_it_behaves_like_to(:it_has_behavior, 'has behavior:') # end # # # allows the user to include a shared example group like: # # RSpec.describe Entity do # it_has_behavior 'sortability' do # let(:sortable) { Entity.new } # end # end # # # which is reported in the output as: # # Entity # # has behavior: sortability # # ...sortability examples here # # @note Use with caution. This extends the language used in your # specs, but does not add any additional documentation. We use this # in RSpec to define `it_should_behave_like` (for backward # compatibility), but we also add docs for that method. def alias_it_behaves_like_to(new_name, report_label='') RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label) end alias_method :alias_it_should_behave_like_to, :alias_it_behaves_like_to # Adds key/value pairs to the `inclusion_filter`. If `args` # includes any symbols that are not part of the hash, each symbol # is treated as a key in the hash with the value `true`. # # ### Note # # Filters set using this method can be overridden from the command line # or config files (e.g. `.rspec`). # # @example # # Given this declaration. # describe "something", :foo => 'bar' do # # ... # end # # # Any of the following will include that group. # config.filter_run_including :foo => 'bar' # config.filter_run_including :foo => /^ba/ # config.filter_run_including :foo => lambda {|v| v == 'bar'} # config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'} # # # Given a proc with an arity of 1, the lambda is passed the value # # related to the key, e.g. # config.filter_run_including :foo => lambda {|v| v == 'bar'} # # # Given a proc with an arity of 2, the lambda is passed the value # # related to the key, and the metadata itself e.g. # config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'} # # filter_run_including :foo # same as filter_run_including :foo => true def filter_run_including(*args) meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering) filter_manager.include_with_low_priority meta static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta) end alias_method :filter_run, :filter_run_including # Applies the provided filter only if any of examples match, in constrast # to {#filter_run}, which always applies even if no examples match, in # which case no examples will be run. This allows you to leave configured # filters in place that are intended only for temporary use. The most common # example is focus filtering: `config.filter_run_when_matching :focus`. # With that configured, you can temporarily focus an example or group # by tagging it with `:focus` metadata, or prefixing it with an `f` # (as in `fdescribe`, `fcontext` and `fit`) since those are aliases for # `describe`/`context`/`it` with `:focus` metadata. def filter_run_when_matching(*args) when_first_matching_example_defined(*args) do filter_run(*args) end end # Clears and reassigns the `inclusion_filter`. Set to `nil` if you don't # want any inclusion filter at all. # # ### Warning # # This overrides any inclusion filters/tags set on the command line or in # configuration files. def inclusion_filter=(filter) meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering) filter_manager.include_only meta end alias_method :filter=, :inclusion_filter= # Returns the `inclusion_filter`. If none has been set, returns an empty # hash. def inclusion_filter filter_manager.inclusions end alias_method :filter, :inclusion_filter # Adds key/value pairs to the `exclusion_filter`. If `args` # includes any symbols that are not part of the hash, each symbol # is treated as a key in the hash with the value `true`. # # ### Note # # Filters set using this method can be overridden from the command line # or config files (e.g. `.rspec`). # # @example # # Given this declaration. # describe "something", :foo => 'bar' do # # ... # end # # # Any of the following will exclude that group. # config.filter_run_excluding :foo => 'bar' # config.filter_run_excluding :foo => /^ba/ # config.filter_run_excluding :foo => lambda {|v| v == 'bar'} # config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'} # # # Given a proc with an arity of 1, the lambda is passed the value # # related to the key, e.g. # config.filter_run_excluding :foo => lambda {|v| v == 'bar'} # # # Given a proc with an arity of 2, the lambda is passed the value # # related to the key, and the metadata itself e.g. # config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'} # # filter_run_excluding :foo # same as filter_run_excluding :foo => true def filter_run_excluding(*args) meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering) filter_manager.exclude_with_low_priority meta static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta) end # Clears and reassigns the `exclusion_filter`. Set to `nil` if you don't # want any exclusion filter at all. # # ### Warning # # This overrides any exclusion filters/tags set on the command line or in # configuration files. def exclusion_filter=(filter) meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering) filter_manager.exclude_only meta end # Returns the `exclusion_filter`. If none has been set, returns an empty # hash. def exclusion_filter filter_manager.exclusions end # Tells RSpec to include `mod` in example groups. Methods defined in # `mod` are exposed to examples (not example groups). Use `filters` to # constrain the groups or examples in which to include the module. # # @example # # module AuthenticationHelpers # def login_as(user) # # ... # end # end # # module PreferencesHelpers # def preferences(user, preferences = {}) # # ... # end # end # # module UserHelpers # def users(username) # # ... # end # end # # RSpec.configure do |config| # config.include(UserHelpers) # included in all groups # # # included in examples with `:preferences` metadata # config.include(PreferenceHelpers, :preferences) # # # included in examples with `:type => :request` metadata # config.include(AuthenticationHelpers, :type => :request) # end # # describe "edit profile", :preferences, :type => :request do # it "can be viewed by owning user" do # login_as preferences(users(:jdoe), :lang => 'es') # get "/profiles/jdoe" # assert_select ".username", :text => 'jdoe' # end # end # # @note Filtered module inclusions can also be applied to # individual examples that have matching metadata. Just like # Ruby's object model is that every object has a singleton class # which has only a single instance, RSpec's model is that every # example has a singleton example group containing just the one # example. # # @see #include_context # @see #extend # @see #prepend def include(mod, *filters) define_mixed_in_module(mod, filters, @include_modules, :include) do |group| safe_include(mod, group) end end # Tells RSpec to include the named shared example group in example groups. # Use `filters` to constrain the groups or examples in which to include # the example group. # # @example # # RSpec.shared_context "example admin user" do # let(:admin_user) { create_user(:admin) } # end # # RSpec.shared_context "example guest user" do # let(:guest_user) { create_user(:guest) } # end # # RSpec.configure do |config| # config.include_context "example guest user", :type => :request # config.include_context "example admin user", :admin, :type => :request # end # # RSpec.describe "The admin page", :type => :request do # it "can be viewed by admins", :admin do # login_with admin_user # get "/admin" # expect(response).to be_ok # end # # it "cannot be viewed by guests" do # login_with guest_user # get "/admin" # expect(response).to be_forbidden # end # end # # @note Filtered context inclusions can also be applied to # individual examples that have matching metadata. Just like # Ruby's object model is that every object has a singleton class # which has only a single instance, RSpec's model is that every # example has a singleton example group containing just the one # example. # # @see #include def include_context(shared_group_name, *filters) shared_module = world.shared_example_group_registry.find([:main], shared_group_name) include shared_module, *filters end # Tells RSpec to extend example groups with `mod`. Methods defined in # `mod` are exposed to example groups (not examples). Use `filters` to # constrain the groups to extend. # # Similar to `include`, but behavior is added to example groups, which # are classes, rather than the examples, which are instances of those # classes. # # @example # # module UiHelpers # def run_in_browser # # ... # end # end # # module PermissionHelpers # def define_permissions # # ... # end # end # # RSpec.configure do |config| # config.extend(UiHelpers, :type => :request) # config.extend(PermissionHelpers, :with_permissions, :type => :request) # end # # describe "edit profile", :with_permissions, :type => :request do # run_in_browser # define_permissions # # it "does stuff in the client" do # # ... # end # end # # @see #include # @see #prepend def extend(mod, *filters) define_mixed_in_module(mod, filters, @extend_modules, :extend) do |group| safe_extend(mod, group) end end if RSpec::Support::RubyFeatures.module_prepends_supported? # Tells RSpec to prepend example groups with `mod`. Methods defined in # `mod` are exposed to examples (not example groups). Use `filters` to # constrain the groups in which to prepend the module. # # Similar to `include`, but module is included before the example group's class # in the ancestor chain. # # @example # # module OverrideMod # def override_me # "overridden" # end # end # # RSpec.configure do |config| # config.prepend(OverrideMod, :method => :prepend) # end # # describe "overriding example's class", :method => :prepend do # it "finds the user" do # self.class.class_eval do # def override_me # end # end # override_me # => "overridden" # # ... # end # end # # @see #include # @see #extend def prepend(mod, *filters) define_mixed_in_module(mod, filters, @prepend_modules, :prepend) do |group| safe_prepend(mod, group) end end end # @private # # Used internally to extend a group with modules using `include`, `prepend` and/or # `extend`. def configure_group(group) group.hooks.register_globals(group, hooks) configure_group_with group, @include_modules, :safe_include configure_group_with group, @extend_modules, :safe_extend configure_group_with group, @prepend_modules, :safe_prepend end # @private # # Used internally to extend the singleton class of a single example's # example group instance with modules using `include` and/or `extend`. def configure_example(example, example_hooks) example_hooks.register_global_singleton_context_hooks(example, hooks) singleton_group = example.example_group_instance.singleton_class # We replace the metadata so that SharedExampleGroupModule#included # has access to the example's metadata[:location]. singleton_group.with_replaced_metadata(example.metadata) do modules = @include_modules.items_for(example.metadata) modules.each do |mod| safe_include(mod, example.example_group_instance.singleton_class) end MemoizedHelpers.define_helpers_on(singleton_group) unless modules.empty? end end # @private def requires=(paths) directories = ['lib', default_path].select { |p| File.directory? p } RSpec::Core::RubyProject.add_to_load_path(*directories) paths.each { |path| load_file_handling_errors(:require, path) } @requires += paths end # @private def in_project_source_dir_regex regexes = project_source_dirs.map do |dir| /\A#{Regexp.escape(File.expand_path(dir))}\// end Regexp.union(regexes) end # @private def configure_mock_framework RSpec::Core::ExampleGroup.__send__(:include, mock_framework) conditionally_disable_mocks_monkey_patching end # @private def configure_expectation_framework expectation_frameworks.each do |framework| RSpec::Core::ExampleGroup.__send__(:include, framework) end conditionally_disable_expectations_monkey_patching end # @private def load_spec_files # Note which spec files world is already aware of. # This is generally only needed for when the user runs # `ruby path/to/spec.rb` (and loads `rspec/autorun`) -- # in that case, the spec file was loaded by `ruby` and # isn't loaded by us here so we only know about it because # of an example group being registered in it. world.registered_example_group_files.each do |f| loaded_spec_files << f # the registered files are already expended absolute paths end files_to_run.uniq.each do |f| file = File.expand_path(f) load_file_handling_errors(:load, file) loaded_spec_files << file end @spec_files_loaded = true end # @private DEFAULT_FORMATTER = lambda { |string| string } # Formats the docstring output using the block provided. # # @example # # This will strip the descriptions of both examples and example # # groups. # RSpec.configure do |config| # config.format_docstrings { |s| s.strip } # end def format_docstrings(&block) @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER end # @private def format_docstrings_block @format_docstrings_block ||= DEFAULT_FORMATTER end # @private def self.delegate_to_ordering_manager(*methods) methods.each do |method| define_method method do |*args, &block| ordering_manager.__send__(method, *args, &block) end end end # @!method seed=(value) # # Sets the seed value and sets the default global ordering to random. delegate_to_ordering_manager :seed= # @!method seed # Seed for random ordering (default: generated randomly each run). # # When you run specs with `--order random`, RSpec generates a random seed # for the randomization and prints it to the `output_stream` (assuming # you're using RSpec's built-in formatters). If you discover an ordering # dependency (i.e. examples fail intermittently depending on order), set # this (on Configuration or on the command line with `--seed`) to run # using the same seed while you debug the issue. # # We recommend, actually, that you use the command line approach so you # don't accidentally leave the seed encoded. delegate_to_ordering_manager :seed # @!method order=(value) # # Sets the default global ordering strategy. By default this can be one # of `:defined`, `:random`, but is customizable through the # `register_ordering` API. If order is set to `'rand:<seed>'`, # the seed will also be set. # # @see #register_ordering delegate_to_ordering_manager :order= # @!method register_ordering(name) # # Registers a named ordering strategy that can later be # used to order an example group's subgroups by adding # `:order => <name>` metadata to the example group. # # @param name [Symbol] The name of the ordering. # @yield Block that will order the given examples or example groups # @yieldparam list [Array<RSpec::Core::Example>, # Array<RSpec::Core::ExampleGroup>] The examples or groups to order # @yieldreturn [Array<RSpec::Core::Example>, # Array<RSpec::Core::ExampleGroup>] The re-ordered examples or groups # # @example # RSpec.configure do |rspec| # rspec.register_ordering :reverse do |list| # list.reverse # end # end # # RSpec.describe 'MyClass', :order => :reverse do # # ... # end # # @note Pass the symbol `:global` to set the ordering strategy that # will be used to order the top-level example groups and any example # groups that do not have declared `:order` metadata. # # @example # RSpec.configure do |rspec| # rspec.register_ordering :global do |examples| # acceptance, other = examples.partition do |example| # example.metadata[:type] == :acceptance # end # other + acceptance # end # end # # RSpec.describe 'MyClass', :type => :acceptance do # # will run last # end # # RSpec.describe 'MyClass' do # # will run first # end # delegate_to_ordering_manager :register_ordering # @private delegate_to_ordering_manager :seed_used?, :ordering_registry # Set Ruby warnings on or off. def warnings=(value) $VERBOSE = !!value end # @return [Boolean] Whether or not ruby warnings are enabled. def warnings? $VERBOSE end # @private RAISE_ERROR_WARNING_NOTIFIER = lambda { |message| raise message } # Turns warnings into errors. This can be useful when # you want RSpec to run in a 'strict' no warning situation. # # @example # # RSpec.configure do |rspec| # rspec.raise_on_warning = true # end def raise_on_warning=(value) if value RSpec::Support.warning_notifier = RAISE_ERROR_WARNING_NOTIFIER else RSpec::Support.warning_notifier = RSpec::Support::DEFAULT_WARNING_NOTIFIER end end # Exposes the current running example via the named # helper method. RSpec 2.x exposed this via `example`, # but in RSpec 3.0, the example is instead exposed via # an arg yielded to `it`, `before`, `let`, etc. However, # some extension gems (such as Capybara) depend on the # RSpec 2.x's `example` method, so this config option # can be used to maintain compatibility. # # @param method_name [Symbol] the name of the helper method # # @example # # RSpec.configure do |rspec| # rspec.expose_current_running_example_as :example # end # # RSpec.describe MyClass do # before do # # `example` can be used here because of the above config. # do_something if example.metadata[:type] == "foo" # end # end def expose_current_running_example_as(method_name) ExposeCurrentExample.module_exec do extend RSpec::SharedContext let(method_name) { |ex| ex } end include ExposeCurrentExample end # @private module ExposeCurrentExample; end # Turns deprecation warnings into errors, in order to surface # the full backtrace of the call site. This can be useful when # you need more context to address a deprecation than the # single-line call site normally provided. # # @example # # RSpec.configure do |rspec| # rspec.raise_errors_for_deprecations! # end def raise_errors_for_deprecations! self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new end # Enables zero monkey patching mode for RSpec. It removes monkey # patching of the top-level DSL methods (`describe`, # `shared_examples_for`, etc) onto `main` and `Module`, instead # requiring you to prefix these methods with `RSpec.`. It enables # expect-only syntax for rspec-mocks and rspec-expectations. It # simply disables monkey patching on whatever pieces of RSpec # the user is using. # # @note It configures rspec-mocks and rspec-expectations only # if the user is using those (either explicitly or implicitly # by not setting `mock_with` or `expect_with` to anything else). # # @note If the user uses this options with `mock_with :mocha` # (or similiar) they will still have monkey patching active # in their test environment from mocha. # # @example # # # It disables all monkey patching. # RSpec.configure do |config| # config.disable_monkey_patching! # end # # # Is an equivalent to # RSpec.configure do |config| # config.expose_dsl_globally = false # # config.mock_with :rspec do |mocks| # mocks.syntax = :expect # mocks.patch_marshal_to_support_partial_doubles = false # end # # config.expect_with :rspec do |expectations| # expectations.syntax = :expect # end # end def disable_monkey_patching! self.expose_dsl_globally = false self.disable_monkey_patching = true conditionally_disable_mocks_monkey_patching conditionally_disable_expectations_monkey_patching end # @private attr_accessor :disable_monkey_patching # Defines a callback that can assign derived metadata values. # # @param filters [Array<Symbol>, Hash] metadata filters that determine # which example or group metadata hashes the callback will be triggered # for. If none are given, the callback will be run against the metadata # hashes of all groups and examples. # @yieldparam metadata [Hash] original metadata hash from an example or # group. Mutate this in your block as needed. # # @example # RSpec.configure do |config| # # Tag all groups and examples in the spec/unit directory with # # :type => :unit # config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata| # metadata[:type] = :unit # end # end def define_derived_metadata(*filters, &block) meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering) @derived_metadata_blocks.append(block, meta) end # Defines a callback that runs after the first example with matching # metadata is defined. If no examples are defined with matching metadata, # it will not get called at all. # # This can be used to ensure some setup is performed (such as bootstrapping # a DB or loading a specific file that adds significantly to the boot time) # if needed (as indicated by the presence of an example with matching metadata) # but avoided otherwise. # # @example # RSpec.configure do |config| # config.when_first_matching_example_defined(:db) do # # Load a support file that does some heavyweight setup, # # including bootstrapping the DB, but only if we have loaded # # any examples tagged with `:db`. # require 'support/db' # end # end def when_first_matching_example_defined(*filters) specified_meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering) callback = lambda do |example_or_group_meta| # Example groups do not have `:example_group` metadata # (instead they have `:parent_example_group` metadata). return unless example_or_group_meta.key?(:example_group) # Ensure the callback only fires once. @derived_metadata_blocks.delete(callback, specified_meta) yield end @derived_metadata_blocks.append(callback, specified_meta) end # @private def apply_derived_metadata_to(metadata) already_run_blocks = Set.new # We loop and attempt to re-apply metadata blocks to support cascades # (e.g. where a derived bit of metadata triggers the application of # another piece of derived metadata, etc) # # We limit our looping to 200 times as a way to detect infinitely recursing derived metadata blocks. # It's hard to imagine a valid use case for a derived metadata cascade greater than 200 iterations. 200.times do return if @derived_metadata_blocks.items_for(metadata).all? do |block| already_run_blocks.include?(block).tap do |skip_block| block.call(metadata) unless skip_block already_run_blocks << block end end end # If we got here, then `@derived_metadata_blocks.items_for(metadata).all?` never returned # `true` above and we treat this as an attempt to recurse infinitely. It's better to fail # with a clear # error than hang indefinitely, which is what would happen if we didn't limit # the looping above. raise SystemStackError, "Attempted to recursively derive metadata indefinitely." end # Defines a `before` hook. See {Hooks#before} for full docs. # # This method differs from {Hooks#before} in only one way: it supports # the `:suite` scope. Hooks with the `:suite` scope will be run once before # the first example of the entire suite is executed. Conditions passed along # with `:suite` are effectively ignored. # # @see #prepend_before # @see #after # @see #append_after def before(scope=nil, *meta, &block) handle_suite_hook(scope, meta) do @before_suite_hooks << Hooks::BeforeHook.new(block, {}) end || begin # defeat Ruby 2.5 lazy proc allocation to ensure # the methods below are passed the same proc instances # so `Hook` equality is preserved. For more info, see: # https://bugs.ruby-lang.org/issues/14045#note-5 block.__id__ add_hook_to_existing_matching_groups(meta, scope) { |g| g.before(scope, *meta, &block) } super(scope, *meta, &block) end end alias_method :append_before, :before # Adds `block` to the start of the list of `before` blocks in the same # scope (`:example`, `:context`, or `:suite`), in contrast to {#before}, # which adds the hook to the end of the list. # # See {Hooks#before} for full `before` hook docs. # # This method differs from {Hooks#prepend_before} in only one way: it supports # the `:suite` scope. Hooks with the `:suite` scope will be run once before # the first example of the entire suite is executed. Conditions passed along # with `:suite` are effectively ignored. # # @see #before # @see #after # @see #append_after def prepend_before(scope=nil, *meta, &block) handle_suite_hook(scope, meta) do @before_suite_hooks.unshift Hooks::BeforeHook.new(block, {}) end || begin # defeat Ruby 2.5 lazy proc allocation to ensure # the methods below are passed the same proc instances # so `Hook` equality is preserved.
{'commit': "diff --git a/lib/rspec/core/configuration.rb b/lib/rspec/core/configuration.rb\nindex 2c2c8d2a..82822f04 100644\n--- a/lib/rspec/core/configuration.rb\n+++ b/lib/rspec/core/configuration.rb\n@@ -1031,7 +1031,7 @@ module RSpec\n           formatter_ref\n         elsif string_const?(formatter_ref)\n           begin\n-            formatter_ref.scan(/(?:::|^)(\\w+)/).flatten.inject(Object) { |const,string| const.const_get string }\n+            formatter_ref.gsub(/^::/,'').split('::').inject(Object) { |const,string| const.const_get string }\n           rescue NameError\n             require( path_for(formatter_ref) ) ? retry : raise\n           end\n", 'commit_subject': 'refactor to gsub', 'repo_name': 'rspec/rspec-core', 'committer': {'name': 'Jon Rowe', 'email': 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d@jonrowe.co.uk', 'time_sec': '1380864856', 'tz_offset': '600', 'date': {'seconds': '1380864856'}}, 'commit_tree': '7edd5640f619635887b1637489866f7d94b54ef7', 'commit_message': 'refactor to gsub\n', 'language_name': 'HTML', 'license': 'mit', 'hunks': "@@ -1031,7 +1031,7 @@ module RSpec\n           formatter_ref\n         elsif string_const?(formatter_ref)\n           begin\n-            formatter_ref.scan(/(?:::|^)(\\w+)/).flatten.inject(Object) { |const,string| const.const_get string }\n+            formatter_ref.gsub(/^::/,'').split('::').inject(Object) { |const,string| const.const_get string }\n           rescue NameError\n             require( path_for(formatter_ref) ) ? retry : raise\n           end\n", 'addition_count': 1, 'deletion_count': 1, 'src_file': 'a/lib/rspec/core/configuration.rb', 'tgt_file': 'b/lib/rspec/core/configuration.rb', 'file_extension': '.rb', 'before_file': 'RSpec::Support.require_rspec_core "backtrace_formatter"\nRSpec::Support.require_rspec_core "ruby_project"\nRSpec::Support.require_rspec_core "formatters/deprecation_formatter"\nRSpec::Support.require_rspec_core "output_wrapper"\n\nmodule RSpec\n  module Core\n    # rubocop:disable Metrics/ClassLength\n\n    # Stores runtime configuration information.\n    #\n    # Configuration options are loaded from multiple files and joined together\n    # with command-line switches and the `SPEC_OPTS` environment variable.\n    #\n    # Precedence order (where later entries overwrite earlier entries on\n    # conflicts):\n    #\n    #   * Global (`$XDG_CONFIG_HOME/rspec/options`, or `~/.rspec` if it does\n    #     not exist)\n    #   * Project-specific (`./.rspec`)\n    #   * Local (`./.rspec-local`)\n    #   * Command-line options\n    #   * `SPEC_OPTS`\n    #\n    # For example, an option set in the local file will override an option set\n    # in your global file.\n    #\n    # The global, project-specific and local files can all be overridden with a\n    # separate custom file using the --options command-line parameter.\n    #\n    # @example Standard settings\n    #     RSpec.configure do |c|\n    #       c.drb          = true\n    #       c.drb_port     = 1234\n    #       c.default_path = \'behavior\'\n    #     end\n    #\n    # @example Hooks\n    #     RSpec.configure do |c|\n    #       c.before(:suite)   { establish_connection }\n    #       c.before(:example) { log_in_as :authorized }\n    #       c.around(:example) { |ex| Database.transaction(&ex) }\n    #     end\n    #\n    # @see RSpec.configure\n    # @see Hooks\n    class Configuration\n      include RSpec::Core::Hooks\n\n      # Module that holds `attr_reader` declarations. It\'s in a separate\n      # module to allow us to override those methods and use `super`.\n      # @private\n      Readers = Module.new\n      include Readers\n\n      # @private\n      class MustBeConfiguredBeforeExampleGroupsError < StandardError; end\n\n      # @private\n      def self.define_reader(name)\n        Readers.class_eval do\n          remove_method name if method_defined?(name)\n          attr_reader name\n        end\n\n        define_method(name) { value_for(name) { super() } }\n      end\n\n      # @private\n      def self.define_alias(name, alias_name)\n        alias_method alias_name, name\n        alias_method "#{alias_name}=", "#{name}="\n        define_predicate alias_name\n      end\n\n      # @private\n      def self.define_predicate(name)\n        define_method "#{name}?" do\n          !!send(name)\n        end\n      end\n\n      # @private\n      #\n      # Invoked by the `add_setting` instance method. Use that method on a\n      # `Configuration` instance rather than this class method.\n      def self.add_setting(name, opts={})\n        raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)\n        attr_writer name\n        add_read_only_setting name\n\n        Array(opts[:alias_with]).each do |alias_name|\n          define_alias(name, alias_name)\n        end\n      end\n\n      # @private\n      #\n      # As `add_setting` but only add the reader.\n      def self.add_read_only_setting(name, opts={})\n        raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)\n        define_reader name\n        define_predicate name\n      end\n\n      # @macro [attach] add_setting\n      #   @!attribute [rw] $1\n      #\n      # @macro [attach] define_reader\n      #   @!attribute [r] $1\n\n      # @macro add_setting\n      # Path to use if no path is provided to the `rspec` command (default:\n      # `"spec"`). Allows you to just type `rspec` instead of `rspec spec` to\n      # run all the examples in the `spec` directory.\n      #\n      # @note Other scripts invoking `rspec` indirectly will ignore this\n      #   setting.\n      # @return [String]\n      add_read_only_setting :default_path\n      def default_path=(path)\n        project_source_dirs << path\n        @default_path = path\n      end\n\n      # @macro add_setting\n      # Run examples over DRb (default: `false`). RSpec doesn\'t supply the DRb\n      # server, but you can use tools like spork.\n      # @return [Boolean]\n      add_setting :drb\n\n      # @macro add_setting\n      # The drb_port (default: nil).\n      add_setting :drb_port\n\n      # @macro add_setting\n      # Default: `$stderr`.\n      add_setting :error_stream\n\n      # Indicates if the DSL has been exposed off of modules and `main`.\n      # Default: true\n      # @return [Boolean]\n      def expose_dsl_globally?\n        Core::DSL.exposed_globally?\n      end\n\n      # Use this to expose the core RSpec DSL via `Module` and the `main`\n      # object. It will be set automatically but you can override it to\n      # remove the DSL.\n      # Default: true\n      def expose_dsl_globally=(value)\n        if value\n          Core::DSL.expose_globally!\n          Core::SharedExampleGroup::TopLevelDSL.expose_globally!\n        else\n          Core::DSL.remove_globally!\n          Core::SharedExampleGroup::TopLevelDSL.remove_globally!\n        end\n      end\n\n      # Determines where deprecation warnings are printed.\n      # Defaults to `$stderr`.\n      # @return [IO, String] IO or filename to write to\n      define_reader :deprecation_stream\n\n      # Determines where deprecation warnings are printed.\n      # @param value [IO, String] IO to write to or filename to write to\n      def deprecation_stream=(value)\n        if @reporter && !value.equal?(@deprecation_stream)\n          warn "RSpec\'s reporter has already been initialized with " \\\n            "#{deprecation_stream.inspect} as the deprecation stream, so your change to "\\\n            "`deprecation_stream` will be ignored. You should configure it earlier for " \\\n            "it to take effect, or use the `--deprecation-out` CLI option. " \\\n            "(Called from #{CallerFilter.first_non_rspec_line})"\n        else\n          @deprecation_stream = value\n        end\n      end\n\n      # @macro define_reader\n      # The file path to use for persisting example statuses. Necessary for the\n      # `--only-failures` and `--next-failure` CLI options.\n      #\n      # @overload example_status_persistence_file_path\n      #   @return [String] the file path\n      # @overload example_status_persistence_file_path=(value)\n      #   @param value [String] the file path\n      define_reader :example_status_persistence_file_path\n\n      # Sets the file path to use for persisting example statuses. Necessary for the\n      # `--only-failures` and `--next-failure` CLI options.\n      def example_status_persistence_file_path=(value)\n        @example_status_persistence_file_path = value\n        clear_values_derived_from_example_status_persistence_file_path\n      end\n\n      # @macro define_reader\n      # Indicates if the `--only-failures` (or `--next-failure`) flag is being used.\n      define_reader :only_failures\n      alias_method :only_failures?, :only_failures\n\n      # @private\n      def only_failures_but_not_configured?\n        only_failures? && !example_status_persistence_file_path\n      end\n\n      # @macro define_reader\n      # If specified, indicates the number of failures required before cleaning\n      # up and exit (default: `nil`). Can also be `true` to fail and exit on first\n      # failure\n      define_reader :fail_fast\n\n      # @see fail_fast\n      def fail_fast=(value)\n        case value\n        when true, \'true\'\n          @fail_fast = true\n        when false, \'false\', 0\n          @fail_fast = false\n        when nil\n          @fail_fast = nil\n        else\n          @fail_fast = value.to_i\n\n          if value.to_i == 0\n            # TODO: in RSpec 4, consider raising an error here.\n            RSpec.warning "Cannot set `RSpec.configuration.fail_fast`" \\\n              " to `#{value.inspect}`. Only `true`, `false`, `nil` and integers" \\\n              " are valid values."\n            @fail_fast = true\n          end\n        end\n      end\n\n      # @macro add_setting\n      # Prints the formatter output of your suite without running any\n      # examples or hooks.\n      add_setting :dry_run\n\n      # @macro add_setting\n      # The exit code to return if there are any failures (default: 1).\n      # @return [Integer]\n      add_setting :failure_exit_code\n\n      # @macro add_setting\n      # The exit code to return if there are any errors outside examples (default: failure_exit_code)\n      # @return [Integer]\n      add_setting :error_exit_code\n\n      # @macro add_setting\n      # Whether or not to fail when there are no RSpec examples (default: false).\n      # @return [Boolean]\n      add_setting :fail_if_no_examples\n\n      # @macro define_reader\n      # Indicates files configured to be required.\n      # @return [Array<String>]\n      define_reader :requires\n\n      # @macro define_reader\n      # Returns dirs that have been prepended to the load path by the `-I`\n      # command line option.\n      # @return [Array<String>]\n      define_reader :libs\n\n      # @macro add_setting\n      # Determines where RSpec will send its output.\n      # Default: `$stdout`.\n      # @return [IO, String]\n      define_reader :output_stream\n\n      # Set the output stream for reporter.\n      # @attr value [IO, String] IO to write to or filename to write to, defaults to $stdout\n      def output_stream=(value)\n        if @reporter && !value.equal?(@output_stream)\n          warn "RSpec\'s reporter has already been initialized with " \\\n            "#{output_stream.inspect} as the output stream, so your change to "\\\n            "`output_stream` will be ignored. You should configure it earlier for " \\\n            "it to take effect. (Called from #{CallerFilter.first_non_rspec_line})"\n        else\n          @output_stream = value\n          output_wrapper.output = @output_stream\n        end\n      end\n\n      # @macro define_reader\n      # Load files matching this pattern (default: `\'**{,/*/**}/*_spec.rb\'`).\n      # @return [String]\n      define_reader :pattern\n\n      # Set pattern to match files to load.\n      # @attr value [String] the filename pattern to filter spec files by\n      def pattern=(value)\n        update_pattern_attr :pattern, value\n      end\n\n      # @macro define_reader\n      # Exclude files matching this pattern.\n      # @return [String]\n      define_reader :exclude_pattern\n\n      # Set pattern to match files to exclude.\n      # @attr value [String] the filename pattern to exclude spec files by\n      def exclude_pattern=(value)\n        update_pattern_attr :exclude_pattern, value\n      end\n\n      # @macro add_setting\n      # Specifies which directories contain the source code for your project.\n      # When a failure occurs, RSpec looks through the backtrace to find a\n      # a line of source to print. It first looks for a line coming from\n      # one of the project source directories so that, for example, it prints\n      # the expectation or assertion call rather than the source code from\n      # the expectation or assertion framework.\n      # @return [Array<String>]\n      add_setting :project_source_dirs\n\n      # @macro add_setting\n      # Report the times for the slowest examples (default: `false`).\n      # Use this to specify the number of examples to include in the profile.\n      # @return [Boolean]\n      attr_writer :profile_examples\n      define_predicate :profile_examples\n\n      # @macro add_setting\n      # Run all examples if none match the configured filters\n      # (default: `false`).\n      # @deprecated Use {#filter_run_when_matching} instead for the specific\n      #   filters that you want to be ignored if none match.\n      add_setting :run_all_when_everything_filtered\n\n      # @macro add_setting\n      # Color to use to indicate success.  Defaults to `:green` but can be set\n      # to one of the following: `[:black, :white, :red, :green, :yellow,\n      # :blue, :magenta, :cyan]`\n      # @return [Symbol]\n      add_setting :success_color\n\n      # @macro add_setting\n      # Color to use to print pending examples.  Defaults to `:yellow` but can\n      # be set to one of the following: `[:black, :white, :red, :green,\n      # :yellow, :blue, :magenta, :cyan]`\n      # @return [Symbol]\n      add_setting :pending_color\n\n      # @macro add_setting\n      # Color to use to indicate failure.  Defaults to `:red` but can be set to\n      # one of the following: `[:black, :white, :red, :green, :yellow, :blue,\n      # :magenta, :cyan]`\n      # @return [Symbol]\n      add_setting :failure_color\n\n      # @macro add_setting\n      # The default output color. Defaults to `:white` but can be set to one of\n      # the following: `[:black, :white, :red, :green, :yellow, :blue,\n      # :magenta, :cyan]`\n      # @return [Symbol]\n      add_setting :default_color\n\n      # @macro add_setting\n      # Color used when a pending example is fixed. Defaults to `:blue` but can\n      # be set to one of the following: `[:black, :white, :red, :green,\n      # :yellow, :blue, :magenta, :cyan]`\n      # @return [Symbol]\n      add_setting :fixed_color\n\n      # @macro add_setting\n      # Color used to print details.  Defaults to `:cyan` but can be set to one\n      # of the following: `[:black, :white, :red, :green, :yellow, :blue,\n      # :magenta, :cyan]`\n      # @return [Symbol]\n      add_setting :detail_color\n\n      # @macro add_setting\n      # Don\'t print filter info i.e. "Run options: include {:focus=>true}"\n      # (default `false`).\n      # return [Boolean]\n      add_setting :silence_filter_announcements\n\n      # @deprecated This config option was added in RSpec 2 to pave the way\n      #   for this being the default behavior in RSpec 3. Now this option is\n      #   a no-op.\n      def treat_symbols_as_metadata_keys_with_true_values=(_value)\n        RSpec.deprecate(\n          "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=",\n          :message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " \\\n                      "is deprecated, it is now set to true as default and " \\\n                      "setting it to false has no effect."\n        )\n      end\n\n      # @macro define_reader\n      # Configures how RSpec treats metadata passed as part of a shared example\n      # group definition. For example, given this shared example group definition:\n      #\n      #     RSpec.shared_context "uses DB", :db => true do\n      #       around(:example) do |ex|\n      #         MyORM.transaction(:rollback => true, &ex)\n      #       end\n      #     end\n      #\n      # ...there are two ways RSpec can treat the `:db => true` metadata, each\n      # of which has a corresponding config option:\n      #\n      # 1. `:trigger_inclusion`: this shared context will be implicitly included\n      #    in any groups (or examples) that have `:db => true` metadata.\n      # 2. `:apply_to_host_groups`: the metadata will be inherited by the metadata\n      #    hash of all host groups and examples.\n      #\n      # `:trigger_inclusion` is the legacy behavior from before RSpec 3.5 but should\n      # be considered deprecated. Instead, you can explicitly include a group with\n      # `include_context`:\n      #\n      #     RSpec.describe "My model" do\n      #       include_context "uses DB"\n      #     end\n      #\n      # ...or you can configure RSpec to include the context based on matching metadata\n      # using an API that mirrors configured module inclusion:\n      #\n      #     RSpec.configure do |rspec|\n      #       rspec.include_context "uses DB", :db => true\n      #     end\n      #\n      # `:apply_to_host_groups` is a new feature of RSpec 3.5 and will be the only\n      # supported behavior in RSpec 4.\n      #\n      # @overload shared_context_metadata_behavior\n      #   @return [:trigger_inclusion, :apply_to_host_groups] the configured behavior\n      # @overload shared_context_metadata_behavior=(value)\n      #   @param value [:trigger_inclusion, :apply_to_host_groups] sets the configured behavior\n      define_reader :shared_context_metadata_behavior\n      # @see shared_context_metadata_behavior\n      def shared_context_metadata_behavior=(value)\n        case value\n        when :trigger_inclusion, :apply_to_host_groups\n          @shared_context_metadata_behavior = value\n        else\n          raise ArgumentError, "Cannot set `RSpec.configuration." \\\n            "shared_context_metadata_behavior` to `#{value.inspect}`. Only " \\\n            "`:trigger_inclusion` and `:apply_to_host_groups` are valid values."\n        end\n      end\n\n      # Record the start time of the spec suite to measure load time.\n      # return [Time]\n      add_setting :start_time\n\n      # @macro add_setting\n      # Use threadsafe options where available.\n      # Currently this will place a mutex around memoized values such as let blocks.\n      # return [Boolean]\n      add_setting :threadsafe\n\n      # @macro add_setting\n      # Maximum count of failed source lines to display in the failure reports.\n      # (default `10`).\n      # return [Integer]\n      add_setting :max_displayed_failure_line_count\n\n      # Determines which bisect runner implementation gets used to run subsets\n      # of the suite during a bisection. Your choices are:\n      #\n      #   - `:shell`: Performs a spec run by shelling out, booting RSpec and your\n      #     application environment each time. This runner is the most widely\n      #     compatible runner, but is not as fast. On platforms that do not\n      #     support forking, this is the default.\n      #   - `:fork`: Pre-boots RSpec and your application environment in a parent\n      #     process, and then forks a child process for each spec run. This runner\n      #     tends to be significantly faster than the `:shell` runner but cannot\n      #     be used in some situations. On platforms that support forking, this\n      #     is the default. If you use this runner, you should ensure that all\n      #     of your one-time setup logic goes in a `before(:suite)` hook instead\n      #     of getting run at the top-level of a file loaded by `--require`.\n      #\n      # @note This option will only be used by `--bisect` if you set it in a file\n      #   loaded via `--require`.\n      #\n      # @return [Symbol]\n      attr_reader :bisect_runner\n      def bisect_runner=(value)\n        if @bisect_runner_class && value != @bisect_runner\n          raise "`config.bisect_runner = #{value.inspect}` can no longer take " \\\n            "effect as the #{@bisect_runner.inspect} bisect runnner is already " \\\n            "in use. This config setting must be set in a file loaded by a " \\\n            "`--require` option (passed at the CLI or in a `.rspec` file) for " \\\n            "it to have any effect."\n        end\n\n        @bisect_runner = value\n      end\n\n      # @private\n      # @deprecated Use {#color_mode} = :on, instead of {#color} with {#tty}\n      add_setting :tty\n      # @private\n      attr_writer :files_to_run\n      # @private\n      attr_accessor :filter_manager, :world\n      # @private\n      attr_accessor :static_config_filter_manager\n      # @private\n      attr_reader :backtrace_formatter, :ordering_manager, :loaded_spec_files\n\n      # rubocop:disable Metrics/AbcSize\n      # rubocop:disable Metrics/MethodLength\n\n      # Build an object to store runtime configuration options and set defaults\n      def initialize\n        # rubocop:disable Style/GlobalVars\n        @start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now\n        # rubocop:enable Style/GlobalVars\n        @expectation_frameworks = []\n        @include_modules = FilterableItemRepository::QueryOptimized.new(:any?)\n        @extend_modules  = FilterableItemRepository::QueryOptimized.new(:any?)\n        @prepend_modules = FilterableItemRepository::QueryOptimized.new(:any?)\n\n        @bisect_runner = RSpec::Support::RubyFeatures.fork_supported? ? :fork : :shell\n        @bisect_runner_class = nil\n\n        @before_suite_hooks = []\n        @after_suite_hooks  = []\n\n        @mock_framework = nil\n        @files_or_directories_to_run = []\n        @loaded_spec_files = Set.new\n        @color = false\n        @color_mode = :automatic\n        @pattern = \'**{,/*/**}/*_spec.rb\'\n        @exclude_pattern = \'\'\n        @failure_exit_code = 1\n        @error_exit_code = nil # so it can be overridden by failure exit code\n        @fail_if_no_examples = false\n        @spec_files_loaded = false\n\n        @backtrace_formatter = BacktraceFormatter.new\n\n        @default_path = \'spec\'\n        @project_source_dirs = %w[ spec lib app ]\n        @deprecation_stream = $stderr\n        @output_stream = $stdout\n        @reporter = nil\n        @reporter_buffer = nil\n        @filter_manager = FilterManager.new\n        @static_config_filter_manager = FilterManager.new\n        @ordering_manager = Ordering::ConfigurationManager.new\n        @preferred_options = {}\n        @failure_color = :red\n        @success_color = :green\n        @pending_color = :yellow\n        @default_color = :white\n        @fixed_color = :blue\n        @detail_color = :cyan\n        @profile_examples = false\n        @requires = []\n        @libs = []\n        @derived_metadata_blocks = FilterableItemRepository::QueryOptimized.new(:any?)\n        @threadsafe = true\n        @max_displayed_failure_line_count = 10\n        @world = World::Null\n        @shared_context_metadata_behavior = :trigger_inclusion\n\n        define_built_in_hooks\n      end\n      # rubocop:enable Metrics/AbcSize\n      # rubocop:enable Metrics/MethodLength\n\n      # @private\n      #\n      # Used to set higher priority option values from the command line.\n      def force(hash)\n        ordering_manager.force(hash)\n        @preferred_options.merge!(hash)\n\n        return unless hash.key?(:example_status_persistence_file_path)\n        clear_values_derived_from_example_status_persistence_file_path\n      end\n\n      # @private\n      def reset\n        @spec_files_loaded = false\n        reset_reporter\n      end\n\n      # @private\n      def reset_reporter\n        @reporter = nil\n        @formatter_loader = nil\n        @output_wrapper = nil\n      end\n\n      # @private\n      def reset_filters\n        self.filter_manager = FilterManager.new\n        filter_manager.include_only(\n          Metadata.deep_hash_dup(static_config_filter_manager.inclusions.rules)\n        )\n        filter_manager.exclude_only(\n          Metadata.deep_hash_dup(static_config_filter_manager.exclusions.rules)\n        )\n      end\n\n      # @overload add_setting(name)\n      # @overload add_setting(name, opts)\n      # @option opts [Symbol] :default\n      #\n      #   Set a default value for the generated getter and predicate methods:\n      #\n      #       add_setting(:foo, :default => "default value")\n      #\n      # @option opts [Symbol] :alias_with\n      #\n      #   Use `:alias_with` to alias the setter, getter, and predicate to\n      #   another name, or names:\n      #\n      #       add_setting(:foo, :alias_with => :bar)\n      #       add_setting(:foo, :alias_with => [:bar, :baz])\n      #\n      # Adds a custom setting to the RSpec.configuration object.\n      #\n      #     RSpec.configuration.add_setting :foo\n      #\n      # Used internally and by extension frameworks like rspec-rails, so they\n      # can add config settings that are domain specific. For example:\n      #\n      #     RSpec.configure do |c|\n      #       c.add_setting :use_transactional_fixtures,\n      #         :default => true,\n      #         :alias_with => :use_transactional_examples\n      #     end\n      #\n      # `add_setting` creates three methods on the configuration object, a\n      # setter, a getter, and a predicate:\n      #\n      #     RSpec.configuration.foo=(value)\n      #     RSpec.configuration.foo\n      #     RSpec.configuration.foo? # Returns true if foo returns anything but nil or false.\n      def add_setting(name, opts={})\n        default = opts.delete(:default)\n        (class << self; self; end).class_exec do\n          add_setting(name, opts)\n        end\n        __send__("#{name}=", default) if default\n      end\n\n      # Returns the configured mock framework adapter module.\n      # @return [Symbol]\n      def mock_framework\n        if @mock_framework.nil?\n          begin\n            mock_with :rspec\n          rescue LoadError\n            mock_with :nothing\n          end\n        end\n        @mock_framework\n      end\n\n      # Delegates to mock_framework=(framework).\n      def mock_framework=(framework)\n        mock_with framework\n      end\n\n      # Regexps used to exclude lines from backtraces.\n      #\n      # Excludes lines from ruby (and jruby) source, installed gems, anything\n      # in any "bin" directory, and any of the RSpec libs (outside gem\n      # installs) by default.\n      #\n      # You can modify the list via the getter, or replace it with the setter.\n      #\n      # To override this behaviour and display a full backtrace, use\n      # `--backtrace` on the command line, in a `.rspec` file, or in the\n      # `rspec_options` attribute of RSpec\'s rake task.\n      # @return [Array<Regexp>]\n      def backtrace_exclusion_patterns\n        @backtrace_formatter.exclusion_patterns\n      end\n\n      # Set regular expressions used to exclude lines in backtrace.\n      # @param patterns [Array<Regexp>] set backtrace_formatter exlusion_patterns\n      def backtrace_exclusion_patterns=(patterns)\n        @backtrace_formatter.exclusion_patterns = patterns\n      end\n\n      # Regexps used to include lines in backtraces.\n      #\n      # Defaults to [Regexp.new Dir.getwd].\n      #\n      # Lines that match an exclusion _and_ an inclusion pattern\n      # will be included.\n      #\n      # You can modify the list via the getter, or replace it with the setter.\n      # @return [Array<Regexp>]\n      def backtrace_inclusion_patterns\n        @backtrace_formatter.inclusion_patterns\n      end\n\n      # Set regular expressions used to include lines in backtrace.\n      # @attr patterns [Array<Regexp>] set backtrace_formatter inclusion_patterns\n      def backtrace_inclusion_patterns=(patterns)\n        @backtrace_formatter.inclusion_patterns = patterns\n      end\n\n      # Adds {#backtrace_exclusion_patterns} that will filter lines from\n      # the named gems from backtraces.\n      #\n      # @param gem_names [Array<String>] Names of the gems to filter\n      #\n      # @example\n      #   RSpec.configure do |config|\n      #     config.filter_gems_from_backtrace "rack", "rake"\n      #   end\n      #\n      # @note The patterns this adds will match the named gems in their common\n      #   locations (e.g. system gems, vendored with bundler, installed as a\n      #   :git dependency with bundler, etc) but is not guaranteed to work for\n      #   all possible gem locations. For example, if you have the gem source\n      #   in a directory with a completely unrelated name, and use bundler\'s\n      #   :path option, this will not filter it.\n      def filter_gems_from_backtrace(*gem_names)\n        gem_names.each do |name|\n          @backtrace_formatter.filter_gem(name)\n        end\n      end\n\n      # @private\n      MOCKING_ADAPTERS = {\n        :rspec    => :RSpec,\n        :flexmock => :Flexmock,\n        :rr       => :RR,\n        :mocha    => :Mocha,\n        :nothing  => :Null\n      }\n\n      # Sets the mock framework adapter module.\n      #\n      # `framework` can be a Symbol or a Module.\n      #\n      # Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the\n      # named framework.\n      #\n      # Given `:nothing`, configures no framework. Use this if you don\'t use\n      # any mocking framework to save a little bit of overhead.\n      #\n      # Given a Module, includes that module in every example group. The module\n      # should adhere to RSpec\'s mock framework adapter API:\n      #\n      #     setup_mocks_for_rspec\n      #       - called before each example\n      #\n      #     verify_mocks_for_rspec\n      #       - called after each example if the example hasn\'t yet failed.\n      #         Framework should raise an exception when expectations fail\n      #\n      #     teardown_mocks_for_rspec\n      #       - called after verify_mocks_for_rspec (even if there are errors)\n      #\n      # If the module responds to `configuration` and `mock_with` receives a\n      # block, it will yield the configuration object to the block e.g.\n      #\n      #     config.mock_with OtherMockFrameworkAdapter do |mod_config|\n      #       mod_config.custom_setting = true\n      #     end\n      def mock_with(framework)\n        framework_module =\n          if framework.is_a?(Module)\n            framework\n          else\n            const_name = MOCKING_ADAPTERS.fetch(framework) do\n              raise ArgumentError,\n                    "Unknown mocking framework: #{framework.inspect}. " \\\n                    "Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}"\n            end\n\n            RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}"\n            RSpec::Core::MockingAdapters.const_get(const_name)\n          end\n\n        new_name, old_name = [framework_module, @mock_framework].map do |mod|\n          mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed\n        end\n\n        unless new_name == old_name\n          assert_no_example_groups_defined(:mock_framework)\n        end\n\n        if block_given?\n          raise "#{framework_module} must respond to `configuration` so that " \\\n                "mock_with can yield it." unless framework_module.respond_to?(:configuration)\n          yield framework_module.configuration\n        end\n\n        @mock_framework = framework_module\n      end\n\n      # Returns the configured expectation framework adapter module(s)\n      def expectation_frameworks\n        if @expectation_frameworks.empty?\n          begin\n            expect_with :rspec\n          rescue LoadError\n            expect_with Module.new\n          end\n        end\n        @expectation_frameworks\n      end\n\n      # Delegates to expect_with(framework).\n      def expectation_framework=(framework)\n        expect_with(framework)\n      end\n\n      # Sets the expectation framework module(s) to be included in each example\n      # group.\n      #\n      # `frameworks` can be `:rspec`, `:test_unit`, `:minitest`, a custom\n      # module, or any combination thereof:\n      #\n      #     config.expect_with :rspec\n      #     config.expect_with :test_unit\n      #     config.expect_with :minitest\n      #     config.expect_with :rspec, :minitest\n      #     config.expect_with OtherExpectationFramework\n      #\n      # RSpec will translate `:rspec`, `:minitest`, and `:test_unit` into the\n      # appropriate modules.\n      #\n      # ## Configuration\n      #\n      # If the module responds to `configuration`, `expect_with` will\n      # yield the `configuration` object if given a block:\n      #\n      #     config.expect_with OtherExpectationFramework do |custom_config|\n      #       custom_config.custom_setting = true\n      #     end\n      def expect_with(*frameworks)\n        modules = frameworks.map do |framework|\n          case framework\n          when Module\n            framework\n          when :rspec\n            require \'rspec/expectations\'\n\n            # Tag this exception class so our exception formatting logic knows\n            # that it satisfies the `MultipleExceptionError` interface.\n            ::RSpec::Expectations::MultipleExpectationsNotMetError.__send__(\n              :include, MultipleExceptionError::InterfaceTag\n            )\n\n            ::RSpec::Matchers\n          when :test_unit\n            require \'rspec/core/test_unit_assertions_adapter\'\n            ::RSpec::Core::TestUnitAssertionsAdapter\n          when :minitest\n            require \'rspec/core/minitest_assertions_adapter\'\n            ::RSpec::Core::MinitestAssertionsAdapter\n          else\n            raise ArgumentError, "#{framework.inspect} is not supported"\n          end\n        end\n\n        if (modules - @expectation_frameworks).any?\n          assert_no_example_groups_defined(:expect_with)\n        end\n\n        if block_given?\n          raise "expect_with only accepts a block with a single argument. " \\\n                "Call expect_with #{modules.length} times, " \\\n                "once with each argument, instead." if modules.length > 1\n          raise "#{modules.first} must respond to `configuration` so that " \\\n                "expect_with can yield it." unless modules.first.respond_to?(:configuration)\n          yield modules.first.configuration\n        end\n\n        @expectation_frameworks.push(*modules)\n      end\n\n      # Check if full backtrace is enabled.\n      # @return [Boolean] is full backtrace enabled\n      def full_backtrace?\n        @backtrace_formatter.full_backtrace?\n      end\n\n      # Toggle full backtrace.\n      # @attr true_or_false [Boolean] toggle full backtrace display\n      def full_backtrace=(true_or_false)\n        @backtrace_formatter.full_backtrace = true_or_false\n      end\n\n      # Enables color output if the output is a TTY.  As of RSpec 3.6, this is\n      # the default behavior and this option is retained only for backwards\n      # compatibility.\n      #\n      # @deprecated No longer recommended because of complex behavior. Instead,\n      #   rely on the fact that TTYs will display color by default, or set\n      #   {#color_mode} to :on to display color on a non-TTY output.\n      # @see color_mode\n      # @see color_enabled?\n      # @return [Boolean]\n      def color\n        value_for(:color) { @color }\n      end\n\n      # The mode for determining whether to display output in color. One of:\n      #\n      # - :automatic - the output will be in color if the output is a TTY (the\n      #   default)\n      # - :on - the output will be in color, whether or not the output is a TTY\n      # - :off - the output will not be in color\n      #\n      # @see color_enabled?\n      # @return [Boolean]\n      def color_mode\n        value_for(:color_mode) { @color_mode }\n      end\n\n      # Check if color is enabled for a particular output.\n      # @param output [IO] an output stream to use, defaults to the current\n      #        `output_stream`\n      # @return [Boolean]\n      def color_enabled?(output=output_stream)\n        case color_mode\n        when :on then true\n        when :off then false\n        else # automatic\n          output_to_tty?(output) || (color && tty?)\n        end\n      end\n\n      # Set the color mode.\n      attr_writer :color_mode\n\n      # Toggle output color.\n      #\n      # @deprecated No longer recommended because of complex behavior. Instead,\n      #   rely on the fact that TTYs will display color by default, or set\n      #   {:color_mode} to :on to display color on a non-TTY output.\n      attr_writer :color\n\n      # @private\n      def libs=(libs)\n        libs.map do |lib|\n          @libs.unshift lib\n          $LOAD_PATH.unshift lib\n        end\n      end\n\n      # Run examples matching on `description` in all files to run.\n      # @param description [String, Regexp] the pattern to filter on\n      def full_description=(description)\n        filter_run :full_description => Regexp.union(*Array(description).map { |d| Regexp.new(d) })\n      end\n\n      # @return [Array] full description filter\n      def full_description\n        filter.fetch :full_description, nil\n      end\n\n      # @overload add_formatter(formatter)\n      # @overload add_formatter(formatter, output)\n      #\n      # @param formatter [Class, String, Object] formatter to use. Can be any of the\n      #   string values supported from the CLI (`p`/`progress`,\n      #   `d`/`doc`/`documentation`, `h`/`html`, or `j`/`json`), any\n      #   class that implements the formatter protocol and has registered\n      #   itself with RSpec as a formatter, or a formatter instance.\n      # @param output [String, IO] where the formatter will write its output.\n      #   Can be an IO object or a string path to a file. If not provided,\n      #   the configured `output_stream` (`$stdout`, by default) will be used.\n      #\n      # Adds a formatter to the set RSpec will use for this run.\n      #\n      # @see RSpec::Core::Formatters::Protocol\n      def add_formatter(formatter, output=output_wrapper)\n        formatter_loader.add(formatter, output)\n      end\n      alias_method :formatter=, :add_formatter\n\n      # The formatter that will be used if no formatter has been set.\n      # Defaults to \'progress\'.\n      def default_formatter\n        formatter_loader.default_formatter\n      end\n\n      # Sets a fallback formatter to use if none other has been set.\n      #\n      # @example\n      #\n      #   RSpec.configure do |rspec|\n      #     rspec.default_formatter = \'doc\'\n      #   end\n      def default_formatter=(value)\n        formatter_loader.default_formatter = value\n      end\n\n      # Returns a duplicate of the formatters currently loaded in\n      # the `FormatterLoader` for introspection.\n      #\n      # Note as this is a duplicate, any mutations will be disregarded.\n      #\n      # @return [Array] the formatters currently loaded\n      def formatters\n        formatter_loader.formatters.dup\n      end\n\n      # @private\n      def formatter_loader\n        @formatter_loader ||= Formatters::Loader.new(Reporter.new(self))\n      end\n\n      # @private\n      #\n      # This buffer is used to capture all messages sent to the reporter during\n      # reporter initialization. It can then replay those messages after the\n      # formatter is correctly initialized. Otherwise, deprecation warnings\n      # during formatter initialization can cause an infinite loop.\n      class DeprecationReporterBuffer\n        def initialize\n          @calls = []\n        end\n\n        def deprecation(*args)\n          @calls << args\n        end\n\n        def play_onto(reporter)\n          @calls.each do |args|\n            reporter.deprecation(*args)\n          end\n          formatter_ref\n        elsif string_const?(formatter_ref)\n          begin\n            formatter_ref.scan(/(?:::|^)(\\w+)/).flatten.inject(Object) { |const,string| const.const_get string }\n          rescue NameError\n            require( path_for(formatter_ref) ) ? retry : raise\n          end\n        @reporter_buffer || @reporter ||=\n          begin\n            @reporter_buffer = DeprecationReporterBuffer.new\n            formatter_loader.prepare_default output_wrapper, deprecation_stream\n            @reporter_buffer.play_onto(formatter_loader.reporter)\n            @reporter_buffer = nil\n            formatter_loader.reporter\n          end\n      end\n\n      # @api private\n      #\n      # Defaults `profile_examples` to 10 examples when `@profile_examples` is\n      # `true`.\n      def profile_examples\n        profile = value_for(:profile_examples) { @profile_examples }\n        if profile && !profile.is_a?(Integer)\n          10\n        else\n          profile\n        end\n      end\n\n      # @private\n      def files_or_directories_to_run=(*files)\n        files = files.flatten\n\n        if (command == \'rspec\' || Runner.running_in_drb?) && default_path && files.empty?\n          files << default_path\n        end\n\n        @files_or_directories_to_run = files\n        @files_to_run = nil\n      end\n\n      # The spec files RSpec will run.\n      # @return [Array] specified files about to run\n      def files_to_run\n        @files_to_run ||= get_files_to_run(@files_or_directories_to_run)\n      end\n\n      # @private\n      def last_run_statuses\n        @last_run_statuses ||= Hash.new(UNKNOWN_STATUS).tap do |statuses|\n          if (path = example_status_persistence_file_path)\n            begin\n              ExampleStatusPersister.load_from(path).inject(statuses) do |hash, example|\n                status = example[:status]\n                status = UNKNOWN_STATUS unless VALID_STATUSES.include?(status)\n                hash[example.fetch(:example_id)] = status\n                hash\n              end\n            rescue SystemCallError => e\n              RSpec.warning "Could not read from #{path.inspect} (configured as " \\\n                            "`config.example_status_persistence_file_path`) due " \\\n                            "to a system error: #{e.inspect}. Please check that " \\\n                            "the config option is set to an accessible, valid " \\\n                            "file path", :call_site => nil\n            end\n          end\n        end\n      end\n\n      # @private\n      UNKNOWN_STATUS = "unknown".freeze\n\n      # @private\n      FAILED_STATUS = "failed".freeze\n\n      # @private\n      PASSED_STATUS = "passed".freeze\n\n      # @private\n      PENDING_STATUS = "pending".freeze\n\n      # @private\n      VALID_STATUSES = [UNKNOWN_STATUS, FAILED_STATUS, PASSED_STATUS, PENDING_STATUS]\n\n      # @private\n      def spec_files_with_failures\n        @spec_files_with_failures ||= last_run_statuses.inject(Set.new) do |files, (id, status)|\n          files << Example.parse_id(id).first if status == FAILED_STATUS\n          files\n        end.to_a\n      end\n\n      # Creates a method that delegates to `example` including the submitted\n      # `args`. Used internally to add variants of `example` like `pending`:\n      # @param name [String] example name alias\n      # @param args [Array<Symbol>, Hash] metadata for the generated example\n      #\n      # @note The specific example alias below (`pending`) is already\n      #   defined for you.\n      # @note Use with caution. This extends the language used in your\n      #   specs, but does not add any additional documentation. We use this\n      #   in RSpec to define methods like `focus` and `xit`, but we also add\n      #   docs for those methods.\n      #\n      # @example\n      #   RSpec.configure do |config|\n      #     config.alias_example_to :pending, :pending => true\n      #   end\n      #\n      #   # This lets you do this:\n      #\n      #   RSpec.describe Thing do\n      #     pending "does something" do\n      #       thing = Thing.new\n      #     end\n      #   end\n      #\n      #   # ... which is the equivalent of\n      #\n      #   RSpec.describe Thing do\n      #     it "does something", :pending => true do\n      #       thing = Thing.new\n      #     end\n      #   end\n      def alias_example_to(name, *args)\n        extra_options = Metadata.build_hash_from(args)\n        RSpec::Core::ExampleGroup.define_example_method(name, extra_options)\n      end\n\n      # Creates a method that defines an example group with the provided\n      # metadata. Can be used to define example group/metadata shortcuts.\n      #\n      # @example\n      #   RSpec.configure do |config|\n      #     config.alias_example_group_to :describe_model, :type => :model\n      #   end\n      #\n      #   shared_context_for "model tests", :type => :model do\n      #     # define common model test helper methods, `let` declarations, etc\n      #   end\n      #\n      #   # This lets you do this:\n      #\n      #   RSpec.describe_model User do\n      #   end\n      #\n      #   # ... which is the equivalent of\n      #\n      #   RSpec.describe User, :type => :model do\n      #   end\n      #\n      # @note The defined aliased will also be added to the top level\n      #       (e.g. `main` and from within modules) if\n      #       `expose_dsl_globally` is set to true.\n      # @see #alias_example_to\n      # @see #expose_dsl_globally=\n      def alias_example_group_to(new_name, *args)\n        extra_options = Metadata.build_hash_from(args)\n        RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options)\n      end\n\n      # Define an alias for it_should_behave_like that allows different\n      # language (like "it_has_behavior" or "it_behaves_like") to be\n      # employed when including shared examples.\n      #\n      # @example\n      #   RSpec.configure do |config|\n      #     config.alias_it_behaves_like_to(:it_has_behavior, \'has behavior:\')\n      #   end\n      #\n      #   # allows the user to include a shared example group like:\n      #\n      #   RSpec.describe Entity do\n      #     it_has_behavior \'sortability\' do\n      #       let(:sortable) { Entity.new }\n      #     end\n      #   end\n      #\n      #   # which is reported in the output as:\n      #   # Entity\n      #   #   has behavior: sortability\n      #   #     ...sortability examples here\n      #\n      # @note Use with caution. This extends the language used in your\n      #   specs, but does not add any additional documentation. We use this\n      #   in RSpec to define `it_should_behave_like` (for backward\n      #   compatibility), but we also add docs for that method.\n      def alias_it_behaves_like_to(new_name, report_label=\'\')\n        RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label)\n      end\n      alias_method :alias_it_should_behave_like_to, :alias_it_behaves_like_to\n\n      # Adds key/value pairs to the `inclusion_filter`. If `args`\n      # includes any symbols that are not part of the hash, each symbol\n      # is treated as a key in the hash with the value `true`.\n      #\n      # ### Note\n      #\n      # Filters set using this method can be overridden from the command line\n      # or config files (e.g. `.rspec`).\n      #\n      # @example\n      #     # Given this declaration.\n      #     describe "something", :foo => \'bar\' do\n      #       # ...\n      #     end\n      #\n      #     # Any of the following will include that group.\n      #     config.filter_run_including :foo => \'bar\'\n      #     config.filter_run_including :foo => /^ba/\n      #     config.filter_run_including :foo => lambda {|v| v == \'bar\'}\n      #     config.filter_run_including :foo => lambda {|v,m| m[:foo] == \'bar\'}\n      #\n      #     # Given a proc with an arity of 1, the lambda is passed the value\n      #     # related to the key, e.g.\n      #     config.filter_run_including :foo => lambda {|v| v == \'bar\'}\n      #\n      #     # Given a proc with an arity of 2, the lambda is passed the value\n      #     # related to the key, and the metadata itself e.g.\n      #     config.filter_run_including :foo => lambda {|v,m| m[:foo] == \'bar\'}\n      #\n      #     filter_run_including :foo # same as filter_run_including :foo => true\n      def filter_run_including(*args)\n        meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)\n        filter_manager.include_with_low_priority meta\n        static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta)\n      end\n      alias_method :filter_run, :filter_run_including\n\n      # Applies the provided filter only if any of examples match, in constrast\n      # to {#filter_run}, which always applies even if no examples match, in\n      # which case no examples will be run. This allows you to leave configured\n      # filters in place that are intended only for temporary use. The most common\n      # example is focus filtering: `config.filter_run_when_matching :focus`.\n      # With that configured, you can temporarily focus an example or group\n      # by tagging it with `:focus` metadata, or prefixing it with an `f`\n      # (as in `fdescribe`, `fcontext` and `fit`) since those are aliases for\n      # `describe`/`context`/`it` with `:focus` metadata.\n      def filter_run_when_matching(*args)\n        when_first_matching_example_defined(*args) do\n          filter_run(*args)\n        end\n      end\n\n      # Clears and reassigns the `inclusion_filter`. Set to `nil` if you don\'t\n      # want any inclusion filter at all.\n      #\n      # ### Warning\n      #\n      # This overrides any inclusion filters/tags set on the command line or in\n      # configuration files.\n      def inclusion_filter=(filter)\n        meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)\n        filter_manager.include_only meta\n      end\n\n      alias_method :filter=, :inclusion_filter=\n\n      # Returns the `inclusion_filter`. If none has been set, returns an empty\n      # hash.\n      def inclusion_filter\n        filter_manager.inclusions\n      end\n\n      alias_method :filter, :inclusion_filter\n\n      # Adds key/value pairs to the `exclusion_filter`. If `args`\n      # includes any symbols that are not part of the hash, each symbol\n      # is treated as a key in the hash with the value `true`.\n      #\n      # ### Note\n      #\n      # Filters set using this method can be overridden from the command line\n      # or config files (e.g. `.rspec`).\n      #\n      # @example\n      #     # Given this declaration.\n      #     describe "something", :foo => \'bar\' do\n      #       # ...\n      #     end\n      #\n      #     # Any of the following will exclude that group.\n      #     config.filter_run_excluding :foo => \'bar\'\n      #     config.filter_run_excluding :foo => /^ba/\n      #     config.filter_run_excluding :foo => lambda {|v| v == \'bar\'}\n      #     config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == \'bar\'}\n      #\n      #     # Given a proc with an arity of 1, the lambda is passed the value\n      #     # related to the key, e.g.\n      #     config.filter_run_excluding :foo => lambda {|v| v == \'bar\'}\n      #\n      #     # Given a proc with an arity of 2, the lambda is passed the value\n      #     # related to the key, and the metadata itself e.g.\n      #     config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == \'bar\'}\n      #\n      #     filter_run_excluding :foo # same as filter_run_excluding :foo => true\n      def filter_run_excluding(*args)\n        meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)\n        filter_manager.exclude_with_low_priority meta\n        static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta)\n      end\n\n      # Clears and reassigns the `exclusion_filter`. Set to `nil` if you don\'t\n      # want any exclusion filter at all.\n      #\n      # ### Warning\n      #\n      # This overrides any exclusion filters/tags set on the command line or in\n      # configuration files.\n      def exclusion_filter=(filter)\n        meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)\n        filter_manager.exclude_only meta\n      end\n\n      # Returns the `exclusion_filter`. If none has been set, returns an empty\n      # hash.\n      def exclusion_filter\n        filter_manager.exclusions\n      end\n\n      # Tells RSpec to include `mod` in example groups. Methods defined in\n      # `mod` are exposed to examples (not example groups). Use `filters` to\n      # constrain the groups or examples in which to include the module.\n      #\n      # @example\n      #\n      #     module AuthenticationHelpers\n      #       def login_as(user)\n      #         # ...\n      #       end\n      #     end\n      #\n      #     module PreferencesHelpers\n      #       def preferences(user, preferences = {})\n      #         # ...\n      #       end\n      #     end\n      #\n      #     module UserHelpers\n      #       def users(username)\n      #         # ...\n      #       end\n      #     end\n      #\n      #     RSpec.configure do |config|\n      #       config.include(UserHelpers) # included in all groups\n      #\n      #       # included in examples with `:preferences` metadata\n      #       config.include(PreferenceHelpers, :preferences)\n      #\n      #       # included in examples with `:type => :request` metadata\n      #       config.include(AuthenticationHelpers, :type => :request)\n      #     end\n      #\n      #     describe "edit profile", :preferences, :type => :request do\n      #       it "can be viewed by owning user" do\n      #         login_as preferences(users(:jdoe), :lang => \'es\')\n      #         get "/profiles/jdoe"\n      #         assert_select ".username", :text => \'jdoe\'\n      #       end\n      #     end\n      #\n      # @note Filtered module inclusions can also be applied to\n      #   individual examples that have matching metadata. Just like\n      #   Ruby\'s object model is that every object has a singleton class\n      #   which has only a single instance, RSpec\'s model is that every\n      #   example has a singleton example group containing just the one\n      #   example.\n      #\n      # @see #include_context\n      # @see #extend\n      # @see #prepend\n      def include(mod, *filters)\n        define_mixed_in_module(mod, filters, @include_modules, :include) do |group|\n          safe_include(mod, group)\n        end\n      end\n\n      # Tells RSpec to include the named shared example group in example groups.\n      # Use `filters` to constrain the groups or examples in which to include\n      # the example group.\n      #\n      # @example\n      #\n      #     RSpec.shared_context "example admin user" do\n      #       let(:admin_user) { create_user(:admin) }\n      #     end\n      #\n      #     RSpec.shared_context "example guest user" do\n      #       let(:guest_user) { create_user(:guest) }\n      #     end\n      #\n      #     RSpec.configure do |config|\n      #       config.include_context "example guest user", :type => :request\n      #       config.include_context "example admin user", :admin, :type => :request\n      #     end\n      #\n      #     RSpec.describe "The admin page", :type => :request do\n      #       it "can be viewed by admins", :admin do\n      #         login_with admin_user\n      #         get "/admin"\n      #         expect(response).to be_ok\n      #       end\n      #\n      #       it "cannot be viewed by guests" do\n      #         login_with guest_user\n      #         get "/admin"\n      #         expect(response).to be_forbidden\n      #       end\n      #     end\n      #\n      # @note Filtered context inclusions can also be applied to\n      #   individual examples that have matching metadata. Just like\n      #   Ruby\'s object model is that every object has a singleton class\n      #   which has only a single instance, RSpec\'s model is that every\n      #   example has a singleton example group containing just the one\n      #   example.\n      #\n      # @see #include\n      def include_context(shared_group_name, *filters)\n        shared_module = world.shared_example_group_registry.find([:main], shared_group_name)\n        include shared_module, *filters\n      end\n\n      # Tells RSpec to extend example groups with `mod`. Methods defined in\n      # `mod` are exposed to example groups (not examples). Use `filters` to\n      # constrain the groups to extend.\n      #\n      # Similar to `include`, but behavior is added to example groups, which\n      # are classes, rather than the examples, which are instances of those\n      # classes.\n      #\n      # @example\n      #\n      #     module UiHelpers\n      #       def run_in_browser\n      #         # ...\n      #       end\n      #     end\n      #\n      #     module PermissionHelpers\n      #       def define_permissions\n      #         # ...\n      #       end\n      #     end\n      #\n      #     RSpec.configure do |config|\n      #       config.extend(UiHelpers, :type => :request)\n      #       config.extend(PermissionHelpers, :with_permissions, :type => :request)\n      #     end\n      #\n      #     describe "edit profile", :with_permissions, :type => :request do\n      #       run_in_browser\n      #       define_permissions\n      #\n      #       it "does stuff in the client" do\n      #         # ...\n      #       end\n      #     end\n      #\n      # @see #include\n      # @see #prepend\n      def extend(mod, *filters)\n        define_mixed_in_module(mod, filters, @extend_modules, :extend) do |group|\n          safe_extend(mod, group)\n        end\n      end\n\n      if RSpec::Support::RubyFeatures.module_prepends_supported?\n        # Tells RSpec to prepend example groups with `mod`. Methods defined in\n        # `mod` are exposed to examples (not example groups). Use `filters` to\n        # constrain the groups in which to prepend the module.\n        #\n        # Similar to `include`, but module is included before the example group\'s class\n        # in the ancestor chain.\n        #\n        # @example\n        #\n        #     module OverrideMod\n        #       def override_me\n        #         "overridden"\n        #       end\n        #     end\n        #\n        #     RSpec.configure do |config|\n        #       config.prepend(OverrideMod, :method => :prepend)\n        #     end\n        #\n        #     describe "overriding example\'s class", :method => :prepend do\n        #       it "finds the user" do\n        #         self.class.class_eval do\n        #           def override_me\n        #           end\n        #         end\n        #         override_me # => "overridden"\n        #         # ...\n        #       end\n        #     end\n        #\n        # @see #include\n        # @see #extend\n        def prepend(mod, *filters)\n          define_mixed_in_module(mod, filters, @prepend_modules, :prepend) do |group|\n            safe_prepend(mod, group)\n          end\n        end\n      end\n\n      # @private\n      #\n      # Used internally to extend a group with modules using `include`, `prepend` and/or\n      # `extend`.\n      def configure_group(group)\n        group.hooks.register_globals(group, hooks)\n\n        configure_group_with group, @include_modules, :safe_include\n        configure_group_with group, @extend_modules,  :safe_extend\n        configure_group_with group, @prepend_modules, :safe_prepend\n      end\n\n      # @private\n      #\n      # Used internally to extend the singleton class of a single example\'s\n      # example group instance with modules using `include` and/or `extend`.\n      def configure_example(example, example_hooks)\n        example_hooks.register_global_singleton_context_hooks(example, hooks)\n        singleton_group = example.example_group_instance.singleton_class\n\n        # We replace the metadata so that SharedExampleGroupModule#included\n        # has access to the example\'s metadata[:location].\n        singleton_group.with_replaced_metadata(example.metadata) do\n          modules = @include_modules.items_for(example.metadata)\n          modules.each do |mod|\n            safe_include(mod, example.example_group_instance.singleton_class)\n          end\n\n          MemoizedHelpers.define_helpers_on(singleton_group) unless modules.empty?\n        end\n      end\n\n      # @private\n      def requires=(paths)\n        directories = [\'lib\', default_path].select { |p| File.directory? p }\n        RSpec::Core::RubyProject.add_to_load_path(*directories)\n        paths.each { |path| load_file_handling_errors(:require, path) }\n        @requires += paths\n      end\n\n      # @private\n      def in_project_source_dir_regex\n        regexes = project_source_dirs.map do |dir|\n          /\\A#{Regexp.escape(File.expand_path(dir))}\\//\n        end\n\n        Regexp.union(regexes)\n      end\n\n      # @private\n      def configure_mock_framework\n        RSpec::Core::ExampleGroup.__send__(:include, mock_framework)\n        conditionally_disable_mocks_monkey_patching\n      end\n\n      # @private\n      def configure_expectation_framework\n        expectation_frameworks.each do |framework|\n          RSpec::Core::ExampleGroup.__send__(:include, framework)\n        end\n        conditionally_disable_expectations_monkey_patching\n      end\n\n      # @private\n      def load_spec_files\n        # Note which spec files world is already aware of.\n        # This is generally only needed for when the user runs\n        # `ruby path/to/spec.rb` (and loads `rspec/autorun`) --\n        # in that case, the spec file was loaded by `ruby` and\n        # isn\'t loaded by us here so we only know about it because\n        # of an example group being registered in it.\n        world.registered_example_group_files.each do |f|\n          loaded_spec_files << f # the registered files are already expended absolute paths\n        end\n\n        files_to_run.uniq.each do |f|\n          file = File.expand_path(f)\n          load_file_handling_errors(:load, file)\n          loaded_spec_files << file\n        end\n\n        @spec_files_loaded = true\n      end\n\n      # @private\n      DEFAULT_FORMATTER = lambda { |string| string }\n\n      # Formats the docstring output using the block provided.\n      #\n      # @example\n      #   # This will strip the descriptions of both examples and example\n      #   # groups.\n      #   RSpec.configure do |config|\n      #     config.format_docstrings { |s| s.strip }\n      #   end\n      def format_docstrings(&block)\n        @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER\n      end\n\n      # @private\n      def format_docstrings_block\n        @format_docstrings_block ||= DEFAULT_FORMATTER\n      end\n\n      # @private\n      def self.delegate_to_ordering_manager(*methods)\n        methods.each do |method|\n          define_method method do |*args, &block|\n            ordering_manager.__send__(method, *args, &block)\n          end\n        end\n      end\n\n      # @!method seed=(value)\n      #\n      # Sets the seed value and sets the default global ordering to random.\n      delegate_to_ordering_manager :seed=\n\n      # @!method seed\n      # Seed for random ordering (default: generated randomly each run).\n      #\n      # When you run specs with `--order random`, RSpec generates a random seed\n      # for the randomization and prints it to the `output_stream` (assuming\n      # you\'re using RSpec\'s built-in formatters). If you discover an ordering\n      # dependency (i.e. examples fail intermittently depending on order), set\n      # this (on Configuration or on the command line with `--seed`) to run\n      # using the same seed while you debug the issue.\n      #\n      # We recommend, actually, that you use the command line approach so you\n      # don\'t accidentally leave the seed encoded.\n      delegate_to_ordering_manager :seed\n\n      # @!method order=(value)\n      #\n      # Sets the default global ordering strategy. By default this can be one\n      # of `:defined`, `:random`, but is customizable through the\n      # `register_ordering` API. If order is set to `\'rand:<seed>\'`,\n      # the seed will also be set.\n      #\n      # @see #register_ordering\n      delegate_to_ordering_manager :order=\n\n      # @!method register_ordering(name)\n      #\n      # Registers a named ordering strategy that can later be\n      # used to order an example group\'s subgroups by adding\n      # `:order => <name>` metadata to the example group.\n      #\n      # @param name [Symbol] The name of the ordering.\n      # @yield Block that will order the given examples or example groups\n      # @yieldparam list [Array<RSpec::Core::Example>,\n      #   Array<RSpec::Core::ExampleGroup>] The examples or groups to order\n      # @yieldreturn [Array<RSpec::Core::Example>,\n      #   Array<RSpec::Core::ExampleGroup>] The re-ordered examples or groups\n      #\n      # @example\n      #   RSpec.configure do |rspec|\n      #     rspec.register_ordering :reverse do |list|\n      #       list.reverse\n      #     end\n      #   end\n      #\n      #   RSpec.describe \'MyClass\', :order => :reverse do\n      #     # ...\n      #   end\n      #\n      # @note Pass the symbol `:global` to set the ordering strategy that\n      #   will be used to order the top-level example groups and any example\n      #   groups that do not have declared `:order` metadata.\n      #\n      # @example\n      #   RSpec.configure do |rspec|\n      #     rspec.register_ordering :global do |examples|\n      #       acceptance, other = examples.partition do |example|\n      #         example.metadata[:type] == :acceptance\n      #       end\n      #       other + acceptance\n      #     end\n      #   end\n      #\n      #   RSpec.describe \'MyClass\', :type => :acceptance do\n      #     # will run last\n      #   end\n      #\n      #   RSpec.describe \'MyClass\' do\n      #     # will run first\n      #   end\n      #\n      delegate_to_ordering_manager :register_ordering\n\n      # @private\n      delegate_to_ordering_manager :seed_used?, :ordering_registry\n\n      # Set Ruby warnings on or off.\n      def warnings=(value)\n        $VERBOSE = !!value\n      end\n\n      # @return [Boolean] Whether or not ruby warnings are enabled.\n      def warnings?\n        $VERBOSE\n      end\n\n      # @private\n      RAISE_ERROR_WARNING_NOTIFIER = lambda { |message| raise message }\n\n      # Turns warnings into errors. This can be useful when\n      # you want RSpec to run in a \'strict\' no warning situation.\n      #\n      # @example\n      #\n      #   RSpec.configure do |rspec|\n      #     rspec.raise_on_warning = true\n      #   end\n      def raise_on_warning=(value)\n        if value\n          RSpec::Support.warning_notifier = RAISE_ERROR_WARNING_NOTIFIER\n        else\n          RSpec::Support.warning_notifier = RSpec::Support::DEFAULT_WARNING_NOTIFIER\n        end\n      end\n\n      # Exposes the current running example via the named\n      # helper method. RSpec 2.x exposed this via `example`,\n      # but in RSpec 3.0, the example is instead exposed via\n      # an arg yielded to `it`, `before`, `let`, etc. However,\n      # some extension gems (such as Capybara) depend on the\n      # RSpec 2.x\'s `example` method, so this config option\n      # can be used to maintain compatibility.\n      #\n      # @param method_name [Symbol] the name of the helper method\n      #\n      # @example\n      #\n      #   RSpec.configure do |rspec|\n      #     rspec.expose_current_running_example_as :example\n      #   end\n      #\n      #   RSpec.describe MyClass do\n      #     before do\n      #       # `example` can be used here because of the above config.\n      #       do_something if example.metadata[:type] == "foo"\n      #     end\n      #   end\n      def expose_current_running_example_as(method_name)\n        ExposeCurrentExample.module_exec do\n          extend RSpec::SharedContext\n          let(method_name) { |ex| ex }\n        end\n\n        include ExposeCurrentExample\n      end\n\n      # @private\n      module ExposeCurrentExample; end\n\n      # Turns deprecation warnings into errors, in order to surface\n      # the full backtrace of the call site. This can be useful when\n      # you need more context to address a deprecation than the\n      # single-line call site normally provided.\n      #\n      # @example\n      #\n      #   RSpec.configure do |rspec|\n      #     rspec.raise_errors_for_deprecations!\n      #   end\n      def raise_errors_for_deprecations!\n        self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new\n      end\n\n      # Enables zero monkey patching mode for RSpec. It removes monkey\n      # patching of the top-level DSL methods (`describe`,\n      # `shared_examples_for`, etc) onto `main` and `Module`, instead\n      # requiring you to prefix these methods with `RSpec.`. It enables\n      # expect-only syntax for rspec-mocks and rspec-expectations. It\n      # simply disables monkey patching on whatever pieces of RSpec\n      # the user is using.\n      #\n      # @note It configures rspec-mocks and rspec-expectations only\n      #   if the user is using those (either explicitly or implicitly\n      #   by not setting `mock_with` or `expect_with` to anything else).\n      #\n      # @note If the user uses this options with `mock_with :mocha`\n      #   (or similiar) they will still have monkey patching active\n      #   in their test environment from mocha.\n      #\n      # @example\n      #\n      #   # It disables all monkey patching.\n      #   RSpec.configure do |config|\n      #     config.disable_monkey_patching!\n      #   end\n      #\n      #   # Is an equivalent to\n      #   RSpec.configure do |config|\n      #     config.expose_dsl_globally = false\n      #\n      #     config.mock_with :rspec do |mocks|\n      #       mocks.syntax = :expect\n      #       mocks.patch_marshal_to_support_partial_doubles = false\n      #     end\n      #\n      #     config.expect_with :rspec do |expectations|\n      #       expectations.syntax = :expect\n      #     end\n      #   end\n      def disable_monkey_patching!\n        self.expose_dsl_globally = false\n        self.disable_monkey_patching = true\n        conditionally_disable_mocks_monkey_patching\n        conditionally_disable_expectations_monkey_patching\n      end\n\n      # @private\n      attr_accessor :disable_monkey_patching\n\n      # Defines a callback that can assign derived metadata values.\n      #\n      # @param filters [Array<Symbol>, Hash] metadata filters that determine\n      #   which example or group metadata hashes the callback will be triggered\n      #   for. If none are given, the callback will be run against the metadata\n      #   hashes of all groups and examples.\n      # @yieldparam metadata [Hash] original metadata hash from an example or\n      #   group. Mutate this in your block as needed.\n      #\n      # @example\n      #   RSpec.configure do |config|\n      #     # Tag all groups and examples in the spec/unit directory with\n      #     # :type => :unit\n      #     config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata|\n      #       metadata[:type] = :unit\n      #     end\n      #   end\n      def define_derived_metadata(*filters, &block)\n        meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)\n        @derived_metadata_blocks.append(block, meta)\n      end\n\n      # Defines a callback that runs after the first example with matching\n      # metadata is defined. If no examples are defined with matching metadata,\n      # it will not get called at all.\n      #\n      # This can be used to ensure some setup is performed (such as bootstrapping\n      # a DB or loading a specific file that adds significantly to the boot time)\n      # if needed (as indicated by the presence of an example with matching metadata)\n      # but avoided otherwise.\n      #\n      # @example\n      #   RSpec.configure do |config|\n      #     config.when_first_matching_example_defined(:db) do\n      #       # Load a support file that does some heavyweight setup,\n      #       # including bootstrapping the DB, but only if we have loaded\n      #       # any examples tagged with `:db`.\n      #       require \'support/db\'\n      #     end\n      #   end\n      def when_first_matching_example_defined(*filters)\n        specified_meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)\n\n        callback = lambda do |example_or_group_meta|\n          # Example groups do not have `:example_group` metadata\n          # (instead they have `:parent_example_group` metadata).\n          return unless example_or_group_meta.key?(:example_group)\n\n          # Ensure the callback only fires once.\n          @derived_metadata_blocks.delete(callback, specified_meta)\n\n          yield\n        end\n\n        @derived_metadata_blocks.append(callback, specified_meta)\n      end\n\n      # @private\n      def apply_derived_metadata_to(metadata)\n        already_run_blocks = Set.new\n\n        # We loop and attempt to re-apply metadata blocks to support cascades\n        # (e.g. where a derived bit of metadata triggers the application of\n        # another piece of derived metadata, etc)\n        #\n        # We limit our looping to 200 times as a way to detect infinitely recursing derived metadata blocks.\n        # It\'s hard to imagine a valid use case for a derived metadata cascade greater than 200 iterations.\n        200.times do\n          return if @derived_metadata_blocks.items_for(metadata).all? do |block|\n            already_run_blocks.include?(block).tap do |skip_block|\n              block.call(metadata) unless skip_block\n              already_run_blocks << block\n            end\n          end\n        end\n\n        # If we got here, then `@derived_metadata_blocks.items_for(metadata).all?` never returned\n        # `true` above and we treat this as an attempt to recurse infinitely. It\'s better to fail\n        # with a clear # error than hang indefinitely, which is what would happen if we didn\'t limit\n        # the looping above.\n        raise SystemStackError, "Attempted to recursively derive metadata indefinitely."\n      end\n\n      # Defines a `before` hook. See {Hooks#before} for full docs.\n      #\n      # This method differs from {Hooks#before} in only one way: it supports\n      # the `:suite` scope. Hooks with the `:suite` scope will be run once before\n      # the first example of the entire suite is executed. Conditions passed along\n      # with `:suite` are effectively ignored.\n      #\n      # @see #prepend_before\n      # @see #after\n      # @see #append_after\n      def before(scope=nil, *meta, &block)\n        handle_suite_hook(scope, meta) do\n          @before_suite_hooks << Hooks::BeforeHook.new(block, {})\n        end || begin\n          # defeat Ruby 2.5 lazy proc allocation to ensure\n          # the methods below are passed the same proc instances\n          # so `Hook` equality is preserved. For more info, see:\n          # https://bugs.ruby-lang.org/issues/14045#note-5\n          block.__id__\n\n          add_hook_to_existing_matching_groups(meta, scope) { |g| g.before(scope, *meta, &block) }\n          super(scope, *meta, &block)\n        end\n      end\n      alias_method :append_before, :before\n\n      # Adds `block` to the start of the list of `before` blocks in the same\n      # scope (`:example`, `:context`, or `:suite`), in contrast to {#before},\n      # which adds the hook to the end of the list.\n      #\n      # See {Hooks#before} for full `before` hook docs.\n      #\n      # This method differs from {Hooks#prepend_before} in only one way: it supports\n      # the `:suite` scope. Hooks with the `:suite` scope will be run once before\n      # the first example of the entire suite is executed. Conditions passed along\n      # with `:suite` are effectively ignored.\n      #\n      # @see #before\n      # @see #after\n      # @see #append_after\n      def prepend_before(scope=nil, *meta, &block)\n        handle_suite_hook(scope, meta) do\n          @before_suite_hooks.unshift Hooks::BeforeHook.new(block, {})\n        end || begin\n          # defeat Ruby 2.5 lazy proc allocation to ensure\n          # the methods below are passed the same proc instances\n          # so `Hook` equality is preserved. For more info, see:\n          # https://bugs.ruby-lang.org/issues/14045#note-5\n          block.__id__\n\n          add_hook_to_existing_matching_groups(meta, scope) { |g| g.prepend_before(scope, *meta, &block) }\n          super(scope, *meta, &block)\n        end\n      end\n\n      # Defines a `after` hook. See {Hooks#after} for full docs.\n      #\n      # This method differs from {Hooks#after} in only one way: it supports\n      # the `:suite` scope. Hooks with the `:suite` scope will be run once after\n      # the last example of the entire suite is executed. Conditions passed along\n      # with `:suite` are effectively ignored.\n      #\n      # @see #append_after\n      # @see #before\n      # @see #prepend_before\n      def after(scope=nil, *meta, &block)\n        handle_suite_hook(scope, meta) do\n          @after_suite_hooks.unshift Hooks::AfterHook.new(block, {})\n        end || begin\n          # defeat Ruby 2.5 lazy proc allocation to ensure\n          # the methods below are passed the same proc instances\n          # so `Hook` equality is preserved. For more info, see:\n          # https://bugs.ruby-lang.org/issues/14045#note-5\n          block.__id__\n\n          add_hook_to_existing_matching_groups(meta, scope) { |g| g.after(scope, *meta, &block) }\n          super(scope, *meta, &block)\n        end\n      end\n      alias_method :prepend_after, :after\n\n      # Adds `block` to the end of the list of `after` blocks in the same\n      # scope (`:example`, `:context`, or `:suite`), in contrast to {#after},\n      # which adds the hook to the start of the list.\n      #\n      # See {Hooks#after} for full `after` hook docs.\n      #\n      # This method differs from {Hooks#append_after} in only one way: it supports\n      # the `:suite` scope. Hooks with the `:suite` scope will be run once after\n      # the last example of the entire suite is executed. Conditions passed along\n      # with `:suite` are effectively ignored.\n      #\n      # @see #append_after\n      # @see #before\n      # @see #prepend_before\n      def append_after(scope=nil, *meta, &block)\n        handle_suite_hook(scope, meta) do\n          @after_suite_hooks << Hooks::AfterHook.new(block, {})\n        end || begin\n          # defeat Ruby 2.5 lazy proc allocation to ensure\n          # the methods below are passed the same proc instances\n          # so `Hook` equality is preserved. For more info, see:\n          # https://bugs.ruby-lang.org/issues/14045#note-5\n          block.__id__\n\n          add_hook_to_existing_matching_groups(meta, scope) { |g| g.append_after(scope, *meta, &block) }\n          super(scope, *meta, &block)\n        end\n      end\n\n      # Registers `block` as an `around` hook.\n      #\n      # See {Hooks#around} for full `around` hook docs.\n      def around(scope=nil, *meta, &block)\n        # defeat Ruby 2.5 lazy proc allocation to ensure\n        # the methods below are passed the same proc instances\n        # so `Hook` equality is preserved. For more info, see:\n        # https://bugs.ruby-lang.org/issues/14045#note-5\n        block.__id__\n\n        add_hook_to_existing_matching_groups(meta, scope) { |g| g.around(scope, *meta, &block) }\n        super(scope, *meta, &block)\n      end\n\n      # @private\n      def with_suite_hooks\n        return yield if dry_run?\n\n        begin\n          RSpec.current_scope = :before_suite_hook\n          run_suite_hooks("a `before(:suite)` hook", @before_suite_hooks)\n          yield\n        ensure\n          RSpec.current_scope = :after_suite_hook\n          run_suite_hooks("an `after(:suite)` hook", @after_suite_hooks)\n          RSpec.current_scope = :suite\n        end\n      end\n\n      # @private\n      # Holds the various registered hooks. Here we use a FilterableItemRepository\n      # implementation that is specifically optimized for the read/write patterns\n      # of the config object.\n      def hooks\n        @hooks ||= HookCollections.new(self, FilterableItemRepository::QueryOptimized)\n      end\n\n      # Invokes block before defining an example group\n      def on_example_group_definition(&block)\n        on_example_group_definition_callbacks << block\n      end\n\n      # @api private\n      # Returns an array of blocks to call before defining an example group\n      def on_example_group_definition_callbacks\n        @on_example_group_definition_callbacks ||= []\n      end\n\n      # @private\n      def bisect_runner_class\n        @bisect_runner_class ||= begin\n          case bisect_runner\n          when :fork\n            RSpec::Support.require_rspec_core \'bisect/fork_runner\'\n            Bisect::ForkRunner\n          when :shell\n            RSpec::Support.require_rspec_core \'bisect/shell_runner\'\n            Bisect::ShellRunner\n          else\n            raise "Unsupported value for `bisect_runner` (#{bisect_runner.inspect}). " \\\n                  "Only `:fork` and `:shell` are supported."\n          end\n        end\n      end\n\n    private\n\n      def load_file_handling_errors(method, file)\n        __send__(method, file)\n      rescue LoadError => ex\n        relative_file = Metadata.relative_path(file)\n        suggestions = DidYouMean.new(relative_file).call\n        reporter.notify_non_example_exception(ex, "An error occurred while loading #{relative_file}.#{suggestions}")\n        RSpec.world.wants_to_quit = true\n      rescue Support::AllExceptionsExceptOnesWeMustNotRescue => ex\n        relative_file = Metadata.relative_path(file)\n        reporter.notify_non_example_exception(ex, "An error occurred while loading #{relative_file}.")\n        RSpec.world.wants_to_quit = true\n      rescue SystemExit => ex\n        relative_file = Metadata.relative_path(file)\n        reporter.notify_non_example_exception(\n          ex,\n          "While loading #{relative_file} an `exit` / `raise SystemExit` occurred, RSpec will now quit."\n        )\n        RSpec.world.rspec_is_quitting = true\n        raise ex\n      end\n\n      def handle_suite_hook(scope, meta)\n        return nil unless scope == :suite\n\n        unless meta.empty?\n          # TODO: in RSpec 4, consider raising an error here.\n          # We warn only for backwards compatibility.\n          RSpec.warn_with "WARNING: `:suite` hooks do not support metadata since " \\\n                          "they apply to the suite as a whole rather than " \\\n                          "any individual example or example group that has metadata. " \\\n                          "The metadata you have provided (#{meta.inspect}) will be ignored."\n        end\n\n        yield\n      end\n\n      def run_suite_hooks(hook_description, hooks)\n        context = SuiteHookContext.new(hook_description, reporter)\n\n        hooks.each do |hook|\n          begin\n            hook.run(context)\n          rescue Support::AllExceptionsExceptOnesWeMustNotRescue => ex\n            context.set_exception(ex)\n\n            # Do not run subsequent `before` hooks if one fails.\n            # But for `after` hooks, we run them all so that all\n            # cleanup bits get a chance to complete, minimizing the\n            # chance that resources get left behind.\n            break if hooks.equal?(@before_suite_hooks)\n          end\n        end\n      end\n\n      def get_files_to_run(paths)\n        files = FlatMap.flat_map(paths_to_check(paths)) do |path|\n          path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR\n          File.directory?(path) ? gather_directories(path) : extract_location(path)\n        end.uniq\n\n        return files unless only_failures?\n        relative_files = files.map { |f| Metadata.relative_path(File.expand_path f) }\n        intersection = (relative_files & spec_files_with_failures.to_a)\n        intersection.empty? ? files : intersection\n      end\n\n      def paths_to_check(paths)\n        return paths if pattern_might_load_specs_from_vendored_dirs?\n        paths + [Dir.getwd]\n      end\n\n      def pattern_might_load_specs_from_vendored_dirs?\n        pattern.split(File::SEPARATOR).first.include?(\'**\')\n      end\n\n      def gather_directories(path)\n        include_files = get_matching_files(path, pattern)\n        exclude_files = get_matching_files(path, exclude_pattern)\n        (include_files - exclude_files).uniq\n      end\n\n      def get_matching_files(path, pattern)\n        raw_files = Dir[file_glob_from(path, pattern)]\n        raw_files.map { |file| File.expand_path(file) }.sort\n      end\n\n      def file_glob_from(path, pattern)\n        stripped = "{#{pattern.gsub(/\\s*,\\s*/, \',\')}}"\n        return stripped if pattern =~ /^(\\.\\/)?#{Regexp.escape path}/ || absolute_pattern?(pattern)\n        File.join(path, stripped)\n      end\n\n      if RSpec::Support::OS.windows?\n        # :nocov:\n        def absolute_pattern?(pattern)\n          pattern =~ /\\A[A-Z]:\\\\/ || windows_absolute_network_path?(pattern)\n        end\n\n        def windows_absolute_network_path?(pattern)\n          return false unless ::File::ALT_SEPARATOR\n          pattern.start_with?(::File::ALT_SEPARATOR + ::File::ALT_SEPARATOR)\n        end\n        # :nocov:\n      else\n        def absolute_pattern?(pattern)\n          pattern.start_with?(File::Separator)\n        end\n      end\n\n      def extract_location(path)\n        match = /^(.*?)((?:\\:\\d+)+)$/.match(path)\n\n        if match\n          captures = match.captures\n          path = captures[0]\n          lines = captures[1][1..-1].split(":").map(&:to_i)\n          filter_manager.add_location path, lines\n        else\n          path, scoped_ids = Example.parse_id(path)\n          filter_manager.add_ids(path, scoped_ids.split(/\\s*,\\s*/)) if scoped_ids\n        end\n\n        return [] if path == default_path\n        File.expand_path(path)\n      end\n\n      def command\n        $0.split(File::SEPARATOR).last\n      end\n\n      def value_for(key)\n        @preferred_options.fetch(key) { yield }\n      end\n\n      def define_built_in_hooks\n        around(:example, :aggregate_failures => true) do |procsy|\n          begin\n            aggregate_failures(nil, :hide_backtrace => true, &procsy)\n          rescue Support::AllExceptionsExceptOnesWeMustNotRescue => exception\n            procsy.example.set_aggregate_failures_exception(exception)\n          end\n        end\n      end\n\n      def assert_no_example_groups_defined(config_option)\n        return unless world.example_groups.any?\n\n        raise MustBeConfiguredBeforeExampleGroupsError.new(\n          "RSpec\'s #{config_option} configuration option must be configured before " \\\n          "any example groups are defined, but you have already defined a group."\n        )\n      end\n\n      def output_wrapper\n        @output_wrapper ||= OutputWrapper.new(output_stream)\n      end\n\n      def output_to_tty?(output=output_stream)\n        output.respond_to?(:tty?) && output.tty?\n      end\n\n      def conditionally_disable_mocks_monkey_patching\n        return unless disable_monkey_patching && rspec_mocks_loaded?\n\n        RSpec::Mocks.configuration.tap do |config|\n          config.syntax = :expect\n          config.patch_marshal_to_support_partial_doubles = false\n        end\n      end\n\n      def conditionally_disable_expectations_monkey_patching\n        return unless disable_monkey_patching && rspec_expectations_loaded?\n\n        RSpec::Expectations.configuration.syntax = :expect\n      end\n\n      def rspec_mocks_loaded?\n        defined?(RSpec::Mocks.configuration)\n      end\n\n      def rspec_expectations_loaded?\n        defined?(RSpec::Expectations.configuration)\n      end\n\n      def update_pattern_attr(name, value)\n        if @spec_files_loaded\n          RSpec.warning "Configuring `#{name}` to #{value} has no effect since " \\\n                        "RSpec has already loaded the spec files."\n        end\n\n        instance_variable_set(:"@#{name}", value)\n        @files_to_run = nil\n      end\n\n      def clear_values_derived_from_example_status_persistence_file_path\n        @last_run_statuses = nil\n        @spec_files_with_failures = nil\n      end\n\n      def configure_group_with(group, module_list, application_method)\n        module_list.items_for(group.metadata).each do |mod|\n          __send__(application_method, mod, group)\n        end\n      end\n\n      def add_hook_to_existing_matching_groups(meta, scope, &block)\n        # For example hooks, we have to apply it to each of the top level\n        # groups, even if the groups do not match. When we apply it, we\n        # apply it with the metadata, so it will only apply to examples\n        # in the group that match the metadata.\n        # #2280 for background and discussion.\n        if scope == :example || scope == :each || scope.nil?\n          world.example_groups.each(&block)\n        else\n          meta = Metadata.build_hash_from(meta.dup)\n          on_existing_matching_groups(meta, &block)\n        end\n      end\n\n      def on_existing_matching_groups(meta)\n        world.traverse_example_group_trees_until do |group|\n          metadata_applies_to_group?(meta, group).tap do |applies|\n            yield group if applies\n          end\n        end\n      end\n\n      def metadata_applies_to_group?(meta, group)\n        meta.empty? || MetadataFilter.apply?(:any?, meta, group.metadata)\n      end\n\n      if RSpec::Support::RubyFeatures.module_prepends_supported?\n        def safe_prepend(mod, host)\n          host.__send__(:prepend, mod) unless host < mod\n        end\n      end\n\n      if RUBY_VERSION.to_f >= 1.9\n        def safe_include(mod, host)\n          host.__send__(:include, mod) unless host < mod\n        end\n\n        def safe_extend(mod, host)\n          host.extend(mod) unless host.singleton_class < mod\n        end\n      else # for 1.8.7\n        # :nocov:\n        def safe_include(mod, host)\n          host.__send__(:include, mod) unless host.included_modules.include?(mod)\n        end\n\n        def safe_extend(mod, host)\n          host.extend(mod) unless (class << host; self; end).included_modules.include?(mod)\n        end\n        # :nocov:\n      end\n\n      def define_mixed_in_module(mod, filters, mod_list, config_method, &block)\n        unless Module === mod\n          raise TypeError, "`RSpec.configuration.#{config_method}` expects a module but got: #{mod.inspect}"\n        end\n\n        meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)\n        mod_list.append(mod, meta)\n        on_existing_matching_groups(meta, &block)\n      end\n    end\n    # rubocop:enable Metrics/ClassLength\n  end\nend\n', 'message': 'refactor to gsub\n', 'author_name': 'Jon Rowe', 'lang': 'rb'}