rspec-core 3.8.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (84) hide show
  1. checksums.yaml +7 -0
  2. checksums.yaml.gz.sig +0 -0
  3. data.tar.gz.sig +0 -0
  4. data/.document +5 -0
  5. data/.yardopts +8 -0
  6. data/Changelog.md +2243 -0
  7. data/LICENSE.md +26 -0
  8. data/README.md +384 -0
  9. data/exe/rspec +4 -0
  10. data/lib/rspec/autorun.rb +3 -0
  11. data/lib/rspec/core.rb +185 -0
  12. data/lib/rspec/core/backtrace_formatter.rb +65 -0
  13. data/lib/rspec/core/bisect/coordinator.rb +62 -0
  14. data/lib/rspec/core/bisect/example_minimizer.rb +173 -0
  15. data/lib/rspec/core/bisect/fork_runner.rb +134 -0
  16. data/lib/rspec/core/bisect/server.rb +61 -0
  17. data/lib/rspec/core/bisect/shell_command.rb +126 -0
  18. data/lib/rspec/core/bisect/shell_runner.rb +73 -0
  19. data/lib/rspec/core/bisect/utilities.rb +58 -0
  20. data/lib/rspec/core/configuration.rb +2308 -0
  21. data/lib/rspec/core/configuration_options.rb +233 -0
  22. data/lib/rspec/core/drb.rb +113 -0
  23. data/lib/rspec/core/dsl.rb +98 -0
  24. data/lib/rspec/core/example.rb +656 -0
  25. data/lib/rspec/core/example_group.rb +889 -0
  26. data/lib/rspec/core/example_status_persister.rb +235 -0
  27. data/lib/rspec/core/filter_manager.rb +231 -0
  28. data/lib/rspec/core/flat_map.rb +20 -0
  29. data/lib/rspec/core/formatters.rb +269 -0
  30. data/lib/rspec/core/formatters/base_bisect_formatter.rb +45 -0
  31. data/lib/rspec/core/formatters/base_formatter.rb +70 -0
  32. data/lib/rspec/core/formatters/base_text_formatter.rb +75 -0
  33. data/lib/rspec/core/formatters/bisect_drb_formatter.rb +29 -0
  34. data/lib/rspec/core/formatters/bisect_progress_formatter.rb +157 -0
  35. data/lib/rspec/core/formatters/console_codes.rb +68 -0
  36. data/lib/rspec/core/formatters/deprecation_formatter.rb +223 -0
  37. data/lib/rspec/core/formatters/documentation_formatter.rb +70 -0
  38. data/lib/rspec/core/formatters/exception_presenter.rb +508 -0
  39. data/lib/rspec/core/formatters/fallback_message_formatter.rb +28 -0
  40. data/lib/rspec/core/formatters/helpers.rb +110 -0
  41. data/lib/rspec/core/formatters/html_formatter.rb +153 -0
  42. data/lib/rspec/core/formatters/html_printer.rb +414 -0
  43. data/lib/rspec/core/formatters/html_snippet_extractor.rb +120 -0
  44. data/lib/rspec/core/formatters/json_formatter.rb +102 -0
  45. data/lib/rspec/core/formatters/profile_formatter.rb +68 -0
  46. data/lib/rspec/core/formatters/progress_formatter.rb +29 -0
  47. data/lib/rspec/core/formatters/protocol.rb +182 -0
  48. data/lib/rspec/core/formatters/snippet_extractor.rb +134 -0
  49. data/lib/rspec/core/formatters/syntax_highlighter.rb +91 -0
  50. data/lib/rspec/core/hooks.rb +624 -0
  51. data/lib/rspec/core/invocations.rb +87 -0
  52. data/lib/rspec/core/memoized_helpers.rb +554 -0
  53. data/lib/rspec/core/metadata.rb +498 -0
  54. data/lib/rspec/core/metadata_filter.rb +255 -0
  55. data/lib/rspec/core/minitest_assertions_adapter.rb +31 -0
  56. data/lib/rspec/core/mocking_adapters/flexmock.rb +31 -0
  57. data/lib/rspec/core/mocking_adapters/mocha.rb +57 -0
  58. data/lib/rspec/core/mocking_adapters/null.rb +14 -0
  59. data/lib/rspec/core/mocking_adapters/rr.rb +31 -0
  60. data/lib/rspec/core/mocking_adapters/rspec.rb +32 -0
  61. data/lib/rspec/core/notifications.rb +521 -0
  62. data/lib/rspec/core/option_parser.rb +309 -0
  63. data/lib/rspec/core/ordering.rb +158 -0
  64. data/lib/rspec/core/output_wrapper.rb +29 -0
  65. data/lib/rspec/core/pending.rb +165 -0
  66. data/lib/rspec/core/profiler.rb +34 -0
  67. data/lib/rspec/core/project_initializer.rb +48 -0
  68. data/lib/rspec/core/project_initializer/.rspec +1 -0
  69. data/lib/rspec/core/project_initializer/spec/spec_helper.rb +100 -0
  70. data/lib/rspec/core/rake_task.rb +168 -0
  71. data/lib/rspec/core/reporter.rb +257 -0
  72. data/lib/rspec/core/ruby_project.rb +53 -0
  73. data/lib/rspec/core/runner.rb +199 -0
  74. data/lib/rspec/core/sandbox.rb +37 -0
  75. data/lib/rspec/core/set.rb +54 -0
  76. data/lib/rspec/core/shared_context.rb +55 -0
  77. data/lib/rspec/core/shared_example_group.rb +269 -0
  78. data/lib/rspec/core/shell_escape.rb +49 -0
  79. data/lib/rspec/core/test_unit_assertions_adapter.rb +30 -0
  80. data/lib/rspec/core/version.rb +9 -0
  81. data/lib/rspec/core/warnings.rb +40 -0
  82. data/lib/rspec/core/world.rb +275 -0
  83. metadata +292 -0
  84. metadata.gz.sig +0 -0
@@ -0,0 +1,126 @@
1
+ RSpec::Support.require_rspec_core "shell_escape"
2
+ require 'shellwords'
3
+
4
+ module RSpec
5
+ module Core
6
+ module Bisect
7
+ # Provides an API to generate shell commands to run the suite for a
8
+ # set of locations, using the given bisect server to capture the results.
9
+ # @private
10
+ class ShellCommand
11
+ attr_reader :original_cli_args
12
+
13
+ def initialize(original_cli_args)
14
+ @original_cli_args = original_cli_args.reject { |arg| arg.start_with?("--bisect") }
15
+ end
16
+
17
+ def command_for(locations, server)
18
+ parts = []
19
+
20
+ parts << RUBY << load_path
21
+ parts << open3_safe_escape(RSpec::Core.path_to_executable)
22
+
23
+ parts << "--format" << "bisect-drb"
24
+ parts << "--drb-port" << server.drb_port
25
+
26
+ parts.concat(reusable_cli_options)
27
+ parts.concat(locations.map { |l| open3_safe_escape(l) })
28
+
29
+ parts.join(" ")
30
+ end
31
+
32
+ def repro_command_from(locations)
33
+ parts = []
34
+
35
+ parts.concat environment_repro_parts
36
+ parts << "rspec"
37
+ parts.concat Formatters::Helpers.organize_ids(locations)
38
+ parts.concat original_cli_args_without_locations
39
+
40
+ parts.join(" ")
41
+ end
42
+
43
+ def original_locations
44
+ parsed_original_cli_options.fetch(:files_or_directories_to_run)
45
+ end
46
+
47
+ def bisect_environment_hash
48
+ if ENV.key?('SPEC_OPTS')
49
+ { 'SPEC_OPTS' => spec_opts_without_bisect }
50
+ else
51
+ {}
52
+ end
53
+ end
54
+
55
+ def spec_opts_without_bisect
56
+ Shellwords.join(
57
+ Shellwords.split(ENV.fetch('SPEC_OPTS', '')).reject do |arg|
58
+ arg =~ /^--bisect/
59
+ end
60
+ )
61
+ end
62
+
63
+ private
64
+
65
+ include RSpec::Core::ShellEscape
66
+ # On JRuby, Open3.popen3 does not handle shellescaped args properly:
67
+ # https://github.com/jruby/jruby/issues/2767
68
+ if RSpec::Support::Ruby.jruby?
69
+ # :nocov:
70
+ alias open3_safe_escape quote
71
+ # :nocov:
72
+ else
73
+ alias open3_safe_escape escape
74
+ end
75
+
76
+ def environment_repro_parts
77
+ bisect_environment_hash.map do |k, v|
78
+ %Q(#{k}="#{v}")
79
+ end
80
+ end
81
+
82
+ def reusable_cli_options
83
+ @reusable_cli_options ||= begin
84
+ opts = original_cli_args_without_locations
85
+
86
+ if (port = parsed_original_cli_options[:drb_port])
87
+ opts -= %W[ --drb-port #{port} ]
88
+ end
89
+
90
+ parsed_original_cli_options.fetch(:formatters) { [] }.each do |(name, out)|
91
+ opts -= %W[ --format #{name} -f -f#{name} ]
92
+ opts -= %W[ --out #{out} -o -o#{out} ]
93
+ end
94
+
95
+ opts
96
+ end
97
+ end
98
+
99
+ def original_cli_args_without_locations
100
+ @original_cli_args_without_locations ||= begin
101
+ files_or_dirs = parsed_original_cli_options.fetch(:files_or_directories_to_run)
102
+ @original_cli_args - files_or_dirs
103
+ end
104
+ end
105
+
106
+ def parsed_original_cli_options
107
+ @parsed_original_cli_options ||= Parser.parse(@original_cli_args)
108
+ end
109
+
110
+ def load_path
111
+ @load_path ||= "-I#{$LOAD_PATH.map { |p| open3_safe_escape(p) }.join(':')}"
112
+ end
113
+
114
+ # Path to the currently running Ruby executable, borrowed from Rake:
115
+ # https://github.com/ruby/rake/blob/v10.4.2/lib/rake/file_utils.rb#L8-L12
116
+ # Note that we skip `ENV['RUBY']` because we don't have to deal with running
117
+ # RSpec from within a MRI source repository:
118
+ # https://github.com/ruby/rake/commit/968682759b3b65e42748cd2befb2ff3e982272d9
119
+ RUBY = File.join(
120
+ RbConfig::CONFIG['bindir'],
121
+ RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT']).
122
+ sub(/.*\s.*/m, '"\&"')
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,73 @@
1
+ require 'open3'
2
+ RSpec::Support.require_rspec_core "bisect/server"
3
+
4
+ module RSpec
5
+ module Core
6
+ module Bisect
7
+ # Provides an API to run the suite for a set of locations, using
8
+ # the given bisect server to capture the results.
9
+ #
10
+ # Sets of specs are run by shelling out.
11
+ # @private
12
+ class ShellRunner
13
+ def self.start(shell_command, _spec_runner)
14
+ Server.run do |server|
15
+ yield new(server, shell_command)
16
+ end
17
+ end
18
+
19
+ def self.name
20
+ :shell
21
+ end
22
+
23
+ def initialize(server, shell_command)
24
+ @server = server
25
+ @shell_command = shell_command
26
+ end
27
+
28
+ def run(locations)
29
+ run_locations(locations, original_results.failed_example_ids)
30
+ end
31
+
32
+ def original_results
33
+ @original_results ||= run_locations(@shell_command.original_locations)
34
+ end
35
+
36
+ private
37
+
38
+ def run_locations(*capture_args)
39
+ @server.capture_run_results(*capture_args) do
40
+ run_command @shell_command.command_for([], @server)
41
+ end
42
+ end
43
+
44
+ # `Open3.capture2e` does not work on JRuby:
45
+ # https://github.com/jruby/jruby/issues/2766
46
+ if Open3.respond_to?(:capture2e) && !RSpec::Support::Ruby.jruby?
47
+ def run_command(cmd)
48
+ Open3.capture2e(@shell_command.bisect_environment_hash, cmd).first
49
+ end
50
+ else # for 1.8.7
51
+ # :nocov:
52
+ def run_command(cmd)
53
+ out = err = nil
54
+
55
+ original_spec_opts = ENV['SPEC_OPTS']
56
+ ENV['SPEC_OPTS'] = @shell_command.spec_opts_without_bisect
57
+
58
+ Open3.popen3(cmd) do |_, stdout, stderr|
59
+ # Reading the streams blocks until the process is complete
60
+ out = stdout.read
61
+ err = stderr.read
62
+ end
63
+
64
+ "Stdout:\n#{out}\n\nStderr:\n#{err}"
65
+ ensure
66
+ ENV['SPEC_OPTS'] = original_spec_opts
67
+ end
68
+ # :nocov:
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,58 @@
1
+ module RSpec
2
+ module Core
3
+ module Bisect
4
+ # @private
5
+ ExampleSetDescriptor = Struct.new(:all_example_ids, :failed_example_ids)
6
+
7
+ # @private
8
+ class BisectFailedError < StandardError
9
+ def self.for_failed_spec_run(spec_output)
10
+ new("Failed to get results from the spec run. Spec run output:\n\n" +
11
+ spec_output)
12
+ end
13
+ end
14
+
15
+ # Wraps a `formatter` providing a simple means to notify it in place
16
+ # of an `RSpec::Core::Reporter`, without involving configuration in
17
+ # any way.
18
+ # @private
19
+ class Notifier
20
+ def initialize(formatter)
21
+ @formatter = formatter
22
+ end
23
+
24
+ def publish(event, *args)
25
+ return unless @formatter.respond_to?(event)
26
+ notification = Notifications::CustomNotification.for(*args)
27
+ @formatter.__send__(event, notification)
28
+ end
29
+ end
30
+
31
+ # Wraps a pipe to support sending objects between a child and
32
+ # parent process.
33
+ # @private
34
+ class Channel
35
+ def initialize
36
+ @read_io, @write_io = IO.pipe
37
+ end
38
+
39
+ def send(message)
40
+ packet = Marshal.dump(message)
41
+ @write_io.write("#{packet.bytesize}\n#{packet}")
42
+ end
43
+
44
+ # rubocop:disable Security/MarshalLoad
45
+ def receive
46
+ packet_size = Integer(@read_io.gets)
47
+ Marshal.load(@read_io.read(packet_size))
48
+ end
49
+ # rubocop:enable Security/MarshalLoad
50
+
51
+ def close
52
+ @read_io.close
53
+ @write_io.close
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,2308 @@
1
+ RSpec::Support.require_rspec_core "backtrace_formatter"
2
+ RSpec::Support.require_rspec_core "ruby_project"
3
+ RSpec::Support.require_rspec_core "formatters/deprecation_formatter"
4
+ RSpec::Support.require_rspec_core "output_wrapper"
5
+
6
+ module RSpec
7
+ module Core
8
+ # rubocop:disable Metrics/ClassLength
9
+
10
+ # Stores runtime configuration information.
11
+ #
12
+ # Configuration options are loaded from multiple files and joined together
13
+ # with command-line switches and the `SPEC_OPTS` environment variable.
14
+ #
15
+ # Precedence order (where later entries overwrite earlier entries on
16
+ # conflicts):
17
+ #
18
+ # * Global (`$XDG_CONFIG_HOME/rspec/options`, or `~/.rspec` if it does
19
+ # not exist)
20
+ # * Project-specific (`./.rspec`)
21
+ # * Local (`./.rspec-local`)
22
+ # * Command-line options
23
+ # * `SPEC_OPTS`
24
+ #
25
+ # For example, an option set in the local file will override an option set
26
+ # in your global file.
27
+ #
28
+ # The global, project-specific and local files can all be overridden with a
29
+ # separate custom file using the --options command-line parameter.
30
+ #
31
+ # @example Standard settings
32
+ # RSpec.configure do |c|
33
+ # c.drb = true
34
+ # c.drb_port = 1234
35
+ # c.default_path = 'behavior'
36
+ # end
37
+ #
38
+ # @example Hooks
39
+ # RSpec.configure do |c|
40
+ # c.before(:suite) { establish_connection }
41
+ # c.before(:example) { log_in_as :authorized }
42
+ # c.around(:example) { |ex| Database.transaction(&ex) }
43
+ # end
44
+ #
45
+ # @see RSpec.configure
46
+ # @see Hooks
47
+ class Configuration
48
+ include RSpec::Core::Hooks
49
+
50
+ # Module that holds `attr_reader` declarations. It's in a separate
51
+ # module to allow us to override those methods and use `super`.
52
+ # @private
53
+ Readers = Module.new
54
+ include Readers
55
+
56
+ # @private
57
+ class MustBeConfiguredBeforeExampleGroupsError < StandardError; end
58
+
59
+ # @private
60
+ def self.define_reader(name)
61
+ Readers.class_eval do
62
+ remove_method name if method_defined?(name)
63
+ attr_reader name
64
+ end
65
+
66
+ define_method(name) { value_for(name) { super() } }
67
+ end
68
+
69
+ # @private
70
+ def self.define_aliases(name, alias_name)
71
+ alias_method alias_name, name
72
+ alias_method "#{alias_name}=", "#{name}="
73
+ define_predicate_for alias_name
74
+ end
75
+
76
+ # @private
77
+ def self.define_predicate_for(*names)
78
+ names.each { |name| alias_method "#{name}?", name }
79
+ end
80
+
81
+ # @private
82
+ #
83
+ # Invoked by the `add_setting` instance method. Use that method on a
84
+ # `Configuration` instance rather than this class method.
85
+ def self.add_setting(name, opts={})
86
+ raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)
87
+ attr_writer name
88
+ add_read_only_setting name
89
+
90
+ Array(opts[:alias_with]).each do |alias_name|
91
+ define_aliases(name, alias_name)
92
+ end
93
+ end
94
+
95
+ # @private
96
+ #
97
+ # As `add_setting` but only add the reader.
98
+ def self.add_read_only_setting(name, opts={})
99
+ raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default)
100
+ define_reader name
101
+ define_predicate_for name
102
+ end
103
+
104
+ # @macro [attach] add_setting
105
+ # @!attribute [rw] $1
106
+ #
107
+ # @macro [attach] define_reader
108
+ # @!attribute [r] $1
109
+
110
+ # @macro add_setting
111
+ # Path to use if no path is provided to the `rspec` command (default:
112
+ # `"spec"`). Allows you to just type `rspec` instead of `rspec spec` to
113
+ # run all the examples in the `spec` directory.
114
+ #
115
+ # @note Other scripts invoking `rspec` indirectly will ignore this
116
+ # setting.
117
+ # @return [String]
118
+ add_read_only_setting :default_path
119
+ def default_path=(path)
120
+ project_source_dirs << path
121
+ @default_path = path
122
+ end
123
+
124
+ # @macro add_setting
125
+ # Run examples over DRb (default: `false`). RSpec doesn't supply the DRb
126
+ # server, but you can use tools like spork.
127
+ # @return [Boolean]
128
+ add_setting :drb
129
+
130
+ # @macro add_setting
131
+ # The drb_port (default: nil).
132
+ add_setting :drb_port
133
+
134
+ # @macro add_setting
135
+ # Default: `$stderr`.
136
+ add_setting :error_stream
137
+
138
+ # Indicates if the DSL has been exposed off of modules and `main`.
139
+ # Default: true
140
+ # @return [Boolean]
141
+ def expose_dsl_globally?
142
+ Core::DSL.exposed_globally?
143
+ end
144
+
145
+ # Use this to expose the core RSpec DSL via `Module` and the `main`
146
+ # object. It will be set automatically but you can override it to
147
+ # remove the DSL.
148
+ # Default: true
149
+ def expose_dsl_globally=(value)
150
+ if value
151
+ Core::DSL.expose_globally!
152
+ Core::SharedExampleGroup::TopLevelDSL.expose_globally!
153
+ else
154
+ Core::DSL.remove_globally!
155
+ Core::SharedExampleGroup::TopLevelDSL.remove_globally!
156
+ end
157
+ end
158
+
159
+ # Determines where deprecation warnings are printed.
160
+ # Defaults to `$stderr`.
161
+ # @return [IO, String] IO or filename to write to
162
+ define_reader :deprecation_stream
163
+
164
+ # Determines where deprecation warnings are printed.
165
+ # @param value [IO, String] IO to write to or filename to write to
166
+ def deprecation_stream=(value)
167
+ if @reporter && !value.equal?(@deprecation_stream)
168
+ warn "RSpec's reporter has already been initialized with " \
169
+ "#{deprecation_stream.inspect} as the deprecation stream, so your change to "\
170
+ "`deprecation_stream` will be ignored. You should configure it earlier for " \
171
+ "it to take effect, or use the `--deprecation-out` CLI option. " \
172
+ "(Called from #{CallerFilter.first_non_rspec_line})"
173
+ else
174
+ @deprecation_stream = value
175
+ end
176
+ end
177
+
178
+ # @macro define_reader
179
+ # The file path to use for persisting example statuses. Necessary for the
180
+ # `--only-failures` and `--next-failure` CLI options.
181
+ #
182
+ # @overload example_status_persistence_file_path
183
+ # @return [String] the file path
184
+ # @overload example_status_persistence_file_path=(value)
185
+ # @param value [String] the file path
186
+ define_reader :example_status_persistence_file_path
187
+
188
+ # Sets the file path to use for persisting example statuses. Necessary for the
189
+ # `--only-failures` and `--next-failure` CLI options.
190
+ def example_status_persistence_file_path=(value)
191
+ @example_status_persistence_file_path = value
192
+ clear_values_derived_from_example_status_persistence_file_path
193
+ end
194
+
195
+ # @macro define_reader
196
+ # Indicates if the `--only-failures` (or `--next-failure`) flag is being used.
197
+ define_reader :only_failures
198
+ alias_method :only_failures?, :only_failures
199
+
200
+ # @private
201
+ def only_failures_but_not_configured?
202
+ only_failures? && !example_status_persistence_file_path
203
+ end
204
+
205
+ # @macro add_setting
206
+ # If specified, indicates the number of failures required before cleaning
207
+ # up and exit (default: `nil`).
208
+ add_setting :fail_fast
209
+
210
+ # @macro add_setting
211
+ # Prints the formatter output of your suite without running any
212
+ # examples or hooks.
213
+ add_setting :dry_run
214
+
215
+ # @macro add_setting
216
+ # The exit code to return if there are any failures (default: 1).
217
+ # @return [Integer]
218
+ add_setting :failure_exit_code
219
+
220
+ # @macro add_setting
221
+ # Whether or not to fail when there are no RSpec examples (default: false).
222
+ # @return [Boolean]
223
+ add_setting :fail_if_no_examples
224
+
225
+ # @macro define_reader
226
+ # Indicates files configured to be required.
227
+ # @return [Array<String>]
228
+ define_reader :requires
229
+
230
+ # @macro define_reader
231
+ # Returns dirs that have been prepended to the load path by the `-I`
232
+ # command line option.
233
+ # @return [Array<String>]
234
+ define_reader :libs
235
+
236
+ # @macro add_setting
237
+ # Determines where RSpec will send its output.
238
+ # Default: `$stdout`.
239
+ # @return [IO, String]
240
+ define_reader :output_stream
241
+
242
+ # Set the output stream for reporter.
243
+ # @attr value [IO, String] IO to write to or filename to write to, defaults to $stdout
244
+ def output_stream=(value)
245
+ if @reporter && !value.equal?(@output_stream)
246
+ warn "RSpec's reporter has already been initialized with " \
247
+ "#{output_stream.inspect} as the output stream, so your change to "\
248
+ "`output_stream` will be ignored. You should configure it earlier for " \
249
+ "it to take effect. (Called from #{CallerFilter.first_non_rspec_line})"
250
+ else
251
+ @output_stream = value
252
+ output_wrapper.output = @output_stream
253
+ end
254
+ end
255
+
256
+ # @macro define_reader
257
+ # Load files matching this pattern (default: `'**{,/*/**}/*_spec.rb'`).
258
+ # @return [String]
259
+ define_reader :pattern
260
+
261
+ # Set pattern to match files to load.
262
+ # @attr value [String] the filename pattern to filter spec files by
263
+ def pattern=(value)
264
+ update_pattern_attr :pattern, value
265
+ end
266
+
267
+ # @macro define_reader
268
+ # Exclude files matching this pattern.
269
+ # @return [String]
270
+ define_reader :exclude_pattern
271
+
272
+ # Set pattern to match files to exclude.
273
+ # @attr value [String] the filename pattern to exclude spec files by
274
+ def exclude_pattern=(value)
275
+ update_pattern_attr :exclude_pattern, value
276
+ end
277
+
278
+ # @macro add_setting
279
+ # Specifies which directories contain the source code for your project.
280
+ # When a failure occurs, RSpec looks through the backtrace to find a
281
+ # a line of source to print. It first looks for a line coming from
282
+ # one of the project source directories so that, for example, it prints
283
+ # the expectation or assertion call rather than the source code from
284
+ # the expectation or assertion framework.
285
+ # @return [Array<String>]
286
+ add_setting :project_source_dirs
287
+
288
+ # @macro add_setting
289
+ # Report the times for the slowest examples (default: `false`).
290
+ # Use this to specify the number of examples to include in the profile.
291
+ # @return [Boolean]
292
+ add_setting :profile_examples
293
+
294
+ # @macro add_setting
295
+ # Run all examples if none match the configured filters
296
+ # (default: `false`).
297
+ # @deprecated Use {#filter_run_when_matching} instead for the specific
298
+ # filters that you want to be ignored if none match.
299
+ add_setting :run_all_when_everything_filtered
300
+
301
+ # @macro add_setting
302
+ # Color to use to indicate success. Defaults to `:green` but can be set
303
+ # to one of the following: `[:black, :white, :red, :green, :yellow,
304
+ # :blue, :magenta, :cyan]`
305
+ # @return [Symbol]
306
+ add_setting :success_color
307
+
308
+ # @macro add_setting
309
+ # Color to use to print pending examples. Defaults to `:yellow` but can
310
+ # be set to one of the following: `[:black, :white, :red, :green,
311
+ # :yellow, :blue, :magenta, :cyan]`
312
+ # @return [Symbol]
313
+ add_setting :pending_color
314
+
315
+ # @macro add_setting
316
+ # Color to use to indicate failure. Defaults to `:red` but can be set to
317
+ # one of the following: `[:black, :white, :red, :green, :yellow, :blue,
318
+ # :magenta, :cyan]`
319
+ # @return [Symbol]
320
+ add_setting :failure_color
321
+
322
+ # @macro add_setting
323
+ # The default output color. Defaults to `:white` but can be set to one of
324
+ # the following: `[:black, :white, :red, :green, :yellow, :blue,
325
+ # :magenta, :cyan]`
326
+ # @return [Symbol]
327
+ add_setting :default_color
328
+
329
+ # @macro add_setting
330
+ # Color used when a pending example is fixed. Defaults to `:blue` but can
331
+ # be set to one of the following: `[:black, :white, :red, :green,
332
+ # :yellow, :blue, :magenta, :cyan]`
333
+ # @return [Symbol]
334
+ add_setting :fixed_color
335
+
336
+ # @macro add_setting
337
+ # Color used to print details. Defaults to `:cyan` but can be set to one
338
+ # of the following: `[:black, :white, :red, :green, :yellow, :blue,
339
+ # :magenta, :cyan]`
340
+ # @return [Symbol]
341
+ add_setting :detail_color
342
+
343
+ # @macro add_setting
344
+ # Don't print filter info i.e. "Run options: include {:focus=>true}"
345
+ # (default `false`).
346
+ # return [Boolean]
347
+ add_setting :silence_filter_announcements
348
+
349
+ # @deprecated This config option was added in RSpec 2 to pave the way
350
+ # for this being the default behavior in RSpec 3. Now this option is
351
+ # a no-op.
352
+ def treat_symbols_as_metadata_keys_with_true_values=(_value)
353
+ RSpec.deprecate(
354
+ "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=",
355
+ :message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " \
356
+ "is deprecated, it is now set to true as default and " \
357
+ "setting it to false has no effect."
358
+ )
359
+ end
360
+
361
+ # @macro define_reader
362
+ # Configures how RSpec treats metadata passed as part of a shared example
363
+ # group definition. For example, given this shared example group definition:
364
+ #
365
+ # RSpec.shared_context "uses DB", :db => true do
366
+ # around(:example) do |ex|
367
+ # MyORM.transaction(:rollback => true, &ex)
368
+ # end
369
+ # end
370
+ #
371
+ # ...there are two ways RSpec can treat the `:db => true` metadata, each
372
+ # of which has a corresponding config option:
373
+ #
374
+ # 1. `:trigger_inclusion`: this shared context will be implicitly included
375
+ # in any groups (or examples) that have `:db => true` metadata.
376
+ # 2. `:apply_to_host_groups`: the metadata will be inherited by the metadata
377
+ # hash of all host groups and examples.
378
+ #
379
+ # `:trigger_inclusion` is the legacy behavior from before RSpec 3.5 but should
380
+ # be considered deprecated. Instead, you can explicitly include a group with
381
+ # `include_context`:
382
+ #
383
+ # RSpec.describe "My model" do
384
+ # include_context "uses DB"
385
+ # end
386
+ #
387
+ # ...or you can configure RSpec to include the context based on matching metadata
388
+ # using an API that mirrors configured module inclusion:
389
+ #
390
+ # RSpec.configure do |rspec|
391
+ # rspec.include_context "uses DB", :db => true
392
+ # end
393
+ #
394
+ # `:apply_to_host_groups` is a new feature of RSpec 3.5 and will be the only
395
+ # supported behavior in RSpec 4.
396
+ #
397
+ # @overload shared_context_metadata_behavior
398
+ # @return [:trigger_inclusion, :apply_to_host_groups] the configured behavior
399
+ # @overload shared_context_metadata_behavior=(value)
400
+ # @param value [:trigger_inclusion, :apply_to_host_groups] sets the configured behavior
401
+ define_reader :shared_context_metadata_behavior
402
+ # @see shared_context_metadata_behavior
403
+ def shared_context_metadata_behavior=(value)
404
+ case value
405
+ when :trigger_inclusion, :apply_to_host_groups
406
+ @shared_context_metadata_behavior = value
407
+ else
408
+ raise ArgumentError, "Cannot set `RSpec.configuration." \
409
+ "shared_context_metadata_behavior` to `#{value.inspect}`. Only " \
410
+ "`:trigger_inclusion` and `:apply_to_host_groups` are valid values."
411
+ end
412
+ end
413
+
414
+ # Record the start time of the spec suite to measure load time.
415
+ # return [Time]
416
+ add_setting :start_time
417
+
418
+ # @macro add_setting
419
+ # Use threadsafe options where available.
420
+ # Currently this will place a mutex around memoized values such as let blocks.
421
+ # return [Boolean]
422
+ add_setting :threadsafe
423
+
424
+ # @macro add_setting
425
+ # Maximum count of failed source lines to display in the failure reports.
426
+ # (default `10`).
427
+ # return [Integer]
428
+ add_setting :max_displayed_failure_line_count
429
+
430
+ # Determines which bisect runner implementation gets used to run subsets
431
+ # of the suite during a bisection. Your choices are:
432
+ #
433
+ # - `:shell`: Performs a spec run by shelling out, booting RSpec and your
434
+ # application environment each time. This runner is the most widely
435
+ # compatible runner, but is not as fast. On platforms that do not
436
+ # support forking, this is the default.
437
+ # - `:fork`: Pre-boots RSpec and your application environment in a parent
438
+ # process, and then forks a child process for each spec run. This runner
439
+ # tends to be significantly faster than the `:shell` runner but cannot
440
+ # be used in some situations. On platforms that support forking, this
441
+ # is the default. If you use this runner, you should ensure that all
442
+ # of your one-time setup logic goes in a `before(:suite)` hook instead
443
+ # of getting run at the top-level of a file loaded by `--require`.
444
+ #
445
+ # @note This option will only be used by `--bisect` if you set it in a file
446
+ # loaded via `--require`.
447
+ #
448
+ # @return [Symbol]
449
+ attr_reader :bisect_runner
450
+ def bisect_runner=(value)
451
+ if @bisect_runner_class && value != @bisect_runner
452
+ raise "`config.bisect_runner = #{value.inspect}` can no longer take " \
453
+ "effect as the #{@bisect_runner.inspect} bisect runnner is already " \
454
+ "in use. This config setting must be set in a file loaded by a " \
455
+ "`--require` option (passed at the CLI or in a `.rspec` file) for " \
456
+ "it to have any effect."
457
+ end
458
+
459
+ @bisect_runner = value
460
+ end
461
+
462
+ # @private
463
+ # @deprecated Use {#color_mode} = :on, instead of {#color} with {#tty}
464
+ add_setting :tty
465
+ # @private
466
+ attr_writer :files_to_run
467
+ # @private
468
+ attr_accessor :filter_manager, :world
469
+ # @private
470
+ attr_accessor :static_config_filter_manager
471
+ # @private
472
+ attr_reader :backtrace_formatter, :ordering_manager, :loaded_spec_files
473
+
474
+ # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
475
+
476
+ # Build an object to store runtime configuration options and set defaults
477
+ def initialize
478
+ # rubocop:disable Style/GlobalVars
479
+ @start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now
480
+ # rubocop:enable Style/GlobalVars
481
+ @expectation_frameworks = []
482
+ @include_modules = FilterableItemRepository::QueryOptimized.new(:any?)
483
+ @extend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
484
+ @prepend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
485
+
486
+ @bisect_runner = RSpec::Support::RubyFeatures.fork_supported? ? :fork : :shell
487
+ @bisect_runner_class = nil
488
+
489
+ @before_suite_hooks = []
490
+ @after_suite_hooks = []
491
+
492
+ @mock_framework = nil
493
+ @files_or_directories_to_run = []
494
+ @loaded_spec_files = Set.new
495
+ @color = false
496
+ @color_mode = :automatic
497
+ @pattern = '**{,/*/**}/*_spec.rb'
498
+ @exclude_pattern = ''
499
+ @failure_exit_code = 1
500
+ @fail_if_no_examples = false
501
+ @spec_files_loaded = false
502
+
503
+ @backtrace_formatter = BacktraceFormatter.new
504
+
505
+ @default_path = 'spec'
506
+ @project_source_dirs = %w[ spec lib app ]
507
+ @deprecation_stream = $stderr
508
+ @output_stream = $stdout
509
+ @reporter = nil
510
+ @reporter_buffer = nil
511
+ @filter_manager = FilterManager.new
512
+ @static_config_filter_manager = FilterManager.new
513
+ @ordering_manager = Ordering::ConfigurationManager.new
514
+ @preferred_options = {}
515
+ @failure_color = :red
516
+ @success_color = :green
517
+ @pending_color = :yellow
518
+ @default_color = :white
519
+ @fixed_color = :blue
520
+ @detail_color = :cyan
521
+ @profile_examples = false
522
+ @requires = []
523
+ @libs = []
524
+ @derived_metadata_blocks = FilterableItemRepository::QueryOptimized.new(:any?)
525
+ @threadsafe = true
526
+ @max_displayed_failure_line_count = 10
527
+ @world = World::Null
528
+ @shared_context_metadata_behavior = :trigger_inclusion
529
+
530
+ define_built_in_hooks
531
+ end
532
+ # rubocop:enable Metrics/MethodLength, Metrics/AbcSize
533
+
534
+ # @private
535
+ #
536
+ # Used to set higher priority option values from the command line.
537
+ def force(hash)
538
+ ordering_manager.force(hash)
539
+ @preferred_options.merge!(hash)
540
+
541
+ return unless hash.key?(:example_status_persistence_file_path)
542
+ clear_values_derived_from_example_status_persistence_file_path
543
+ end
544
+
545
+ # @private
546
+ def reset
547
+ @spec_files_loaded = false
548
+ reset_reporter
549
+ end
550
+
551
+ # @private
552
+ def reset_reporter
553
+ @reporter = nil
554
+ @formatter_loader = nil
555
+ @output_wrapper = nil
556
+ end
557
+
558
+ # @private
559
+ def reset_filters
560
+ self.filter_manager = FilterManager.new
561
+ filter_manager.include_only(
562
+ Metadata.deep_hash_dup(static_config_filter_manager.inclusions.rules)
563
+ )
564
+ filter_manager.exclude_only(
565
+ Metadata.deep_hash_dup(static_config_filter_manager.exclusions.rules)
566
+ )
567
+ end
568
+
569
+ # @overload add_setting(name)
570
+ # @overload add_setting(name, opts)
571
+ # @option opts [Symbol] :default
572
+ #
573
+ # Set a default value for the generated getter and predicate methods:
574
+ #
575
+ # add_setting(:foo, :default => "default value")
576
+ #
577
+ # @option opts [Symbol] :alias_with
578
+ #
579
+ # Use `:alias_with` to alias the setter, getter, and predicate to
580
+ # another name, or names:
581
+ #
582
+ # add_setting(:foo, :alias_with => :bar)
583
+ # add_setting(:foo, :alias_with => [:bar, :baz])
584
+ #
585
+ # Adds a custom setting to the RSpec.configuration object.
586
+ #
587
+ # RSpec.configuration.add_setting :foo
588
+ #
589
+ # Used internally and by extension frameworks like rspec-rails, so they
590
+ # can add config settings that are domain specific. For example:
591
+ #
592
+ # RSpec.configure do |c|
593
+ # c.add_setting :use_transactional_fixtures,
594
+ # :default => true,
595
+ # :alias_with => :use_transactional_examples
596
+ # end
597
+ #
598
+ # `add_setting` creates three methods on the configuration object, a
599
+ # setter, a getter, and a predicate:
600
+ #
601
+ # RSpec.configuration.foo=(value)
602
+ # RSpec.configuration.foo
603
+ # RSpec.configuration.foo? # Returns true if foo returns anything but nil or false.
604
+ def add_setting(name, opts={})
605
+ default = opts.delete(:default)
606
+ (class << self; self; end).class_exec do
607
+ add_setting(name, opts)
608
+ end
609
+ __send__("#{name}=", default) if default
610
+ end
611
+
612
+ # Returns the configured mock framework adapter module.
613
+ # @return [Symbol]
614
+ def mock_framework
615
+ if @mock_framework.nil?
616
+ begin
617
+ mock_with :rspec
618
+ rescue LoadError
619
+ mock_with :nothing
620
+ end
621
+ end
622
+ @mock_framework
623
+ end
624
+
625
+ # Delegates to mock_framework=(framework).
626
+ def mock_framework=(framework)
627
+ mock_with framework
628
+ end
629
+
630
+ # Regexps used to exclude lines from backtraces.
631
+ #
632
+ # Excludes lines from ruby (and jruby) source, installed gems, anything
633
+ # in any "bin" directory, and any of the RSpec libs (outside gem
634
+ # installs) by default.
635
+ #
636
+ # You can modify the list via the getter, or replace it with the setter.
637
+ #
638
+ # To override this behaviour and display a full backtrace, use
639
+ # `--backtrace` on the command line, in a `.rspec` file, or in the
640
+ # `rspec_options` attribute of RSpec's rake task.
641
+ # @return [Array<Regexp>]
642
+ def backtrace_exclusion_patterns
643
+ @backtrace_formatter.exclusion_patterns
644
+ end
645
+
646
+ # Set regular expressions used to exclude lines in backtrace.
647
+ # @param patterns [Array<Regexp>] set backtrace_formatter exlusion_patterns
648
+ def backtrace_exclusion_patterns=(patterns)
649
+ @backtrace_formatter.exclusion_patterns = patterns
650
+ end
651
+
652
+ # Regexps used to include lines in backtraces.
653
+ #
654
+ # Defaults to [Regexp.new Dir.getwd].
655
+ #
656
+ # Lines that match an exclusion _and_ an inclusion pattern
657
+ # will be included.
658
+ #
659
+ # You can modify the list via the getter, or replace it with the setter.
660
+ # @return [Array<Regexp>]
661
+ def backtrace_inclusion_patterns
662
+ @backtrace_formatter.inclusion_patterns
663
+ end
664
+
665
+ # Set regular expressions used to include lines in backtrace.
666
+ # @attr patterns [Array<Regexp>] set backtrace_formatter inclusion_patterns
667
+ def backtrace_inclusion_patterns=(patterns)
668
+ @backtrace_formatter.inclusion_patterns = patterns
669
+ end
670
+
671
+ # Adds {#backtrace_exclusion_patterns} that will filter lines from
672
+ # the named gems from backtraces.
673
+ #
674
+ # @param gem_names [Array<String>] Names of the gems to filter
675
+ #
676
+ # @example
677
+ # RSpec.configure do |config|
678
+ # config.filter_gems_from_backtrace "rack", "rake"
679
+ # end
680
+ #
681
+ # @note The patterns this adds will match the named gems in their common
682
+ # locations (e.g. system gems, vendored with bundler, installed as a
683
+ # :git dependency with bundler, etc) but is not guaranteed to work for
684
+ # all possible gem locations. For example, if you have the gem source
685
+ # in a directory with a completely unrelated name, and use bundler's
686
+ # :path option, this will not filter it.
687
+ def filter_gems_from_backtrace(*gem_names)
688
+ gem_names.each do |name|
689
+ @backtrace_formatter.filter_gem(name)
690
+ end
691
+ end
692
+
693
+ # @private
694
+ MOCKING_ADAPTERS = {
695
+ :rspec => :RSpec,
696
+ :flexmock => :Flexmock,
697
+ :rr => :RR,
698
+ :mocha => :Mocha,
699
+ :nothing => :Null
700
+ }
701
+
702
+ # Sets the mock framework adapter module.
703
+ #
704
+ # `framework` can be a Symbol or a Module.
705
+ #
706
+ # Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the
707
+ # named framework.
708
+ #
709
+ # Given `:nothing`, configures no framework. Use this if you don't use
710
+ # any mocking framework to save a little bit of overhead.
711
+ #
712
+ # Given a Module, includes that module in every example group. The module
713
+ # should adhere to RSpec's mock framework adapter API:
714
+ #
715
+ # setup_mocks_for_rspec
716
+ # - called before each example
717
+ #
718
+ # verify_mocks_for_rspec
719
+ # - called after each example if the example hasn't yet failed.
720
+ # Framework should raise an exception when expectations fail
721
+ #
722
+ # teardown_mocks_for_rspec
723
+ # - called after verify_mocks_for_rspec (even if there are errors)
724
+ #
725
+ # If the module responds to `configuration` and `mock_with` receives a
726
+ # block, it will yield the configuration object to the block e.g.
727
+ #
728
+ # config.mock_with OtherMockFrameworkAdapter do |mod_config|
729
+ # mod_config.custom_setting = true
730
+ # end
731
+ def mock_with(framework)
732
+ framework_module =
733
+ if framework.is_a?(Module)
734
+ framework
735
+ else
736
+ const_name = MOCKING_ADAPTERS.fetch(framework) do
737
+ raise ArgumentError,
738
+ "Unknown mocking framework: #{framework.inspect}. " \
739
+ "Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}"
740
+ end
741
+
742
+ RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}"
743
+ RSpec::Core::MockingAdapters.const_get(const_name)
744
+ end
745
+
746
+ new_name, old_name = [framework_module, @mock_framework].map do |mod|
747
+ mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed
748
+ end
749
+
750
+ unless new_name == old_name
751
+ assert_no_example_groups_defined(:mock_framework)
752
+ end
753
+
754
+ if block_given?
755
+ raise "#{framework_module} must respond to `configuration` so that " \
756
+ "mock_with can yield it." unless framework_module.respond_to?(:configuration)
757
+ yield framework_module.configuration
758
+ end
759
+
760
+ @mock_framework = framework_module
761
+ end
762
+
763
+ # Returns the configured expectation framework adapter module(s)
764
+ def expectation_frameworks
765
+ if @expectation_frameworks.empty?
766
+ begin
767
+ expect_with :rspec
768
+ rescue LoadError
769
+ expect_with Module.new
770
+ end
771
+ end
772
+ @expectation_frameworks
773
+ end
774
+
775
+ # Delegates to expect_with(framework).
776
+ def expectation_framework=(framework)
777
+ expect_with(framework)
778
+ end
779
+
780
+ # Sets the expectation framework module(s) to be included in each example
781
+ # group.
782
+ #
783
+ # `frameworks` can be `:rspec`, `:test_unit`, `:minitest`, a custom
784
+ # module, or any combination thereof:
785
+ #
786
+ # config.expect_with :rspec
787
+ # config.expect_with :test_unit
788
+ # config.expect_with :minitest
789
+ # config.expect_with :rspec, :minitest
790
+ # config.expect_with OtherExpectationFramework
791
+ #
792
+ # RSpec will translate `:rspec`, `:minitest`, and `:test_unit` into the
793
+ # appropriate modules.
794
+ #
795
+ # ## Configuration
796
+ #
797
+ # If the module responds to `configuration`, `expect_with` will
798
+ # yield the `configuration` object if given a block:
799
+ #
800
+ # config.expect_with OtherExpectationFramework do |custom_config|
801
+ # custom_config.custom_setting = true
802
+ # end
803
+ def expect_with(*frameworks)
804
+ modules = frameworks.map do |framework|
805
+ case framework
806
+ when Module
807
+ framework
808
+ when :rspec
809
+ require 'rspec/expectations'
810
+
811
+ # Tag this exception class so our exception formatting logic knows
812
+ # that it satisfies the `MultipleExceptionError` interface.
813
+ ::RSpec::Expectations::MultipleExpectationsNotMetError.__send__(
814
+ :include, MultipleExceptionError::InterfaceTag
815
+ )
816
+
817
+ ::RSpec::Matchers
818
+ when :test_unit
819
+ require 'rspec/core/test_unit_assertions_adapter'
820
+ ::RSpec::Core::TestUnitAssertionsAdapter
821
+ when :minitest
822
+ require 'rspec/core/minitest_assertions_adapter'
823
+ ::RSpec::Core::MinitestAssertionsAdapter
824
+ else
825
+ raise ArgumentError, "#{framework.inspect} is not supported"
826
+ end
827
+ end
828
+
829
+ if (modules - @expectation_frameworks).any?
830
+ assert_no_example_groups_defined(:expect_with)
831
+ end
832
+
833
+ if block_given?
834
+ raise "expect_with only accepts a block with a single argument. " \
835
+ "Call expect_with #{modules.length} times, " \
836
+ "once with each argument, instead." if modules.length > 1
837
+ raise "#{modules.first} must respond to `configuration` so that " \
838
+ "expect_with can yield it." unless modules.first.respond_to?(:configuration)
839
+ yield modules.first.configuration
840
+ end
841
+
842
+ @expectation_frameworks.push(*modules)
843
+ end
844
+
845
+ # Check if full backtrace is enabled.
846
+ # @return [Boolean] is full backtrace enabled
847
+ def full_backtrace?
848
+ @backtrace_formatter.full_backtrace?
849
+ end
850
+
851
+ # Toggle full backtrace.
852
+ # @attr true_or_false [Boolean] toggle full backtrace display
853
+ def full_backtrace=(true_or_false)
854
+ @backtrace_formatter.full_backtrace = true_or_false
855
+ end
856
+
857
+ # Enables color output if the output is a TTY. As of RSpec 3.6, this is
858
+ # the default behavior and this option is retained only for backwards
859
+ # compatibility.
860
+ #
861
+ # @deprecated No longer recommended because of complex behavior. Instead,
862
+ # rely on the fact that TTYs will display color by default, or set
863
+ # {#color_mode} to :on to display color on a non-TTY output.
864
+ # @see color_mode
865
+ # @see color_enabled?
866
+ # @return [Boolean]
867
+ def color
868
+ value_for(:color) { @color }
869
+ end
870
+
871
+ # The mode for determining whether to display output in color. One of:
872
+ #
873
+ # - :automatic - the output will be in color if the output is a TTY (the
874
+ # default)
875
+ # - :on - the output will be in color, whether or not the output is a TTY
876
+ # - :off - the output will not be in color
877
+ #
878
+ # @see color_enabled?
879
+ # @return [Boolean]
880
+ def color_mode
881
+ value_for(:color_mode) { @color_mode }
882
+ end
883
+
884
+ # Check if color is enabled for a particular output.
885
+ # @param output [IO] an output stream to use, defaults to the current
886
+ # `output_stream`
887
+ # @return [Boolean]
888
+ def color_enabled?(output=output_stream)
889
+ case color_mode
890
+ when :on then true
891
+ when :off then false
892
+ else # automatic
893
+ output_to_tty?(output) || (color && tty?)
894
+ end
895
+ end
896
+
897
+ # Set the color mode.
898
+ attr_writer :color_mode
899
+
900
+ # Toggle output color.
901
+ #
902
+ # @deprecated No longer recommended because of complex behavior. Instead,
903
+ # rely on the fact that TTYs will display color by default, or set
904
+ # {:color_mode} to :on to display color on a non-TTY output.
905
+ attr_writer :color
906
+
907
+ # @private
908
+ def libs=(libs)
909
+ libs.map do |lib|
910
+ @libs.unshift lib
911
+ $LOAD_PATH.unshift lib
912
+ end
913
+ end
914
+
915
+ # Run examples matching on `description` in all files to run.
916
+ # @param description [String, Regexp] the pattern to filter on
917
+ def full_description=(description)
918
+ filter_run :full_description => Regexp.union(*Array(description).map { |d| Regexp.new(d) })
919
+ end
920
+
921
+ # @return [Array] full description filter
922
+ def full_description
923
+ filter.fetch :full_description, nil
924
+ end
925
+
926
+ # @overload add_formatter(formatter)
927
+ # @overload add_formatter(formatter, output)
928
+ #
929
+ # @param formatter [Class, String, Object] formatter to use. Can be any of the
930
+ # string values supported from the CLI (`p`/`progress`,
931
+ # `d`/`doc`/`documentation`, `h`/`html`, or `j`/`json`), any
932
+ # class that implements the formatter protocol and has registered
933
+ # itself with RSpec as a formatter, or a formatter instance.
934
+ # @param output [String, IO] where the formatter will write its output.
935
+ # Can be an IO object or a string path to a file. If not provided,
936
+ # the configured `output_stream` (`$stdout`, by default) will be used.
937
+ #
938
+ # Adds a formatter to the set RSpec will use for this run.
939
+ #
940
+ # @see RSpec::Core::Formatters::Protocol
941
+ def add_formatter(formatter, output=output_wrapper)
942
+ formatter_loader.add(formatter, output)
943
+ end
944
+ alias_method :formatter=, :add_formatter
945
+
946
+ # The formatter that will be used if no formatter has been set.
947
+ # Defaults to 'progress'.
948
+ def default_formatter
949
+ formatter_loader.default_formatter
950
+ end
951
+
952
+ # Sets a fallback formatter to use if none other has been set.
953
+ #
954
+ # @example
955
+ #
956
+ # RSpec.configure do |rspec|
957
+ # rspec.default_formatter = 'doc'
958
+ # end
959
+ def default_formatter=(value)
960
+ formatter_loader.default_formatter = value
961
+ end
962
+
963
+ # Returns a duplicate of the formatters currently loaded in
964
+ # the `FormatterLoader` for introspection.
965
+ #
966
+ # Note as this is a duplicate, any mutations will be disregarded.
967
+ #
968
+ # @return [Array] the formatters currently loaded
969
+ def formatters
970
+ formatter_loader.formatters.dup
971
+ end
972
+
973
+ # @private
974
+ def formatter_loader
975
+ @formatter_loader ||= Formatters::Loader.new(Reporter.new(self))
976
+ end
977
+
978
+ # @private
979
+ #
980
+ # This buffer is used to capture all messages sent to the reporter during
981
+ # reporter initialization. It can then replay those messages after the
982
+ # formatter is correctly initialized. Otherwise, deprecation warnings
983
+ # during formatter initialization can cause an infinite loop.
984
+ class DeprecationReporterBuffer
985
+ def initialize
986
+ @calls = []
987
+ end
988
+
989
+ def deprecation(*args)
990
+ @calls << args
991
+ end
992
+
993
+ def play_onto(reporter)
994
+ @calls.each do |args|
995
+ reporter.deprecation(*args)
996
+ end
997
+ end
998
+ end
999
+
1000
+ # @return [RSpec::Core::Reporter] the currently configured reporter
1001
+ def reporter
1002
+ # @reporter_buffer should only ever be set in this method to cover
1003
+ # initialization of @reporter.
1004
+ @reporter_buffer || @reporter ||=
1005
+ begin
1006
+ @reporter_buffer = DeprecationReporterBuffer.new
1007
+ formatter_loader.prepare_default output_wrapper, deprecation_stream
1008
+ @reporter_buffer.play_onto(formatter_loader.reporter)
1009
+ @reporter_buffer = nil
1010
+ formatter_loader.reporter
1011
+ end
1012
+ end
1013
+
1014
+ # @api private
1015
+ #
1016
+ # Defaults `profile_examples` to 10 examples when `@profile_examples` is
1017
+ # `true`.
1018
+ def profile_examples
1019
+ profile = value_for(:profile_examples) { @profile_examples }
1020
+ if profile && !profile.is_a?(Integer)
1021
+ 10
1022
+ else
1023
+ profile
1024
+ end
1025
+ end
1026
+
1027
+ # @private
1028
+ def files_or_directories_to_run=(*files)
1029
+ files = files.flatten
1030
+
1031
+ if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty?
1032
+ files << default_path
1033
+ end
1034
+
1035
+ @files_or_directories_to_run = files
1036
+ @files_to_run = nil
1037
+ end
1038
+
1039
+ # The spec files RSpec will run.
1040
+ # @return [Array] specified files about to run
1041
+ def files_to_run
1042
+ @files_to_run ||= get_files_to_run(@files_or_directories_to_run)
1043
+ end
1044
+
1045
+ # @private
1046
+ def last_run_statuses
1047
+ @last_run_statuses ||= Hash.new(UNKNOWN_STATUS).tap do |statuses|
1048
+ if (path = example_status_persistence_file_path)
1049
+ begin
1050
+ ExampleStatusPersister.load_from(path).inject(statuses) do |hash, example|
1051
+ status = example[:status]
1052
+ status = UNKNOWN_STATUS unless VALID_STATUSES.include?(status)
1053
+ hash[example.fetch(:example_id)] = status
1054
+ hash
1055
+ end
1056
+ rescue SystemCallError => e
1057
+ RSpec.warning "Could not read from #{path.inspect} (configured as " \
1058
+ "`config.example_status_persistence_file_path`) due " \
1059
+ "to a system error: #{e.inspect}. Please check that " \
1060
+ "the config option is set to an accessible, valid " \
1061
+ "file path", :call_site => nil
1062
+ end
1063
+ end
1064
+ end
1065
+ end
1066
+
1067
+ # @private
1068
+ UNKNOWN_STATUS = "unknown".freeze
1069
+
1070
+ # @private
1071
+ FAILED_STATUS = "failed".freeze
1072
+
1073
+ # @private
1074
+ PASSED_STATUS = "passed".freeze
1075
+
1076
+ # @private
1077
+ PENDING_STATUS = "pending".freeze
1078
+
1079
+ # @private
1080
+ VALID_STATUSES = [UNKNOWN_STATUS, FAILED_STATUS, PASSED_STATUS, PENDING_STATUS]
1081
+
1082
+ # @private
1083
+ def spec_files_with_failures
1084
+ @spec_files_with_failures ||= last_run_statuses.inject(Set.new) do |files, (id, status)|
1085
+ files << Example.parse_id(id).first if status == FAILED_STATUS
1086
+ files
1087
+ end.to_a
1088
+ end
1089
+
1090
+ # Creates a method that delegates to `example` including the submitted
1091
+ # `args`. Used internally to add variants of `example` like `pending`:
1092
+ # @param name [String] example name alias
1093
+ # @param args [Array<Symbol>, Hash] metadata for the generated example
1094
+ #
1095
+ # @note The specific example alias below (`pending`) is already
1096
+ # defined for you.
1097
+ # @note Use with caution. This extends the language used in your
1098
+ # specs, but does not add any additional documentation. We use this
1099
+ # in RSpec to define methods like `focus` and `xit`, but we also add
1100
+ # docs for those methods.
1101
+ #
1102
+ # @example
1103
+ # RSpec.configure do |config|
1104
+ # config.alias_example_to :pending, :pending => true
1105
+ # end
1106
+ #
1107
+ # # This lets you do this:
1108
+ #
1109
+ # describe Thing do
1110
+ # pending "does something" do
1111
+ # thing = Thing.new
1112
+ # end
1113
+ # end
1114
+ #
1115
+ # # ... which is the equivalent of
1116
+ #
1117
+ # describe Thing do
1118
+ # it "does something", :pending => true do
1119
+ # thing = Thing.new
1120
+ # end
1121
+ # end
1122
+ def alias_example_to(name, *args)
1123
+ extra_options = Metadata.build_hash_from(args)
1124
+ RSpec::Core::ExampleGroup.define_example_method(name, extra_options)
1125
+ end
1126
+
1127
+ # Creates a method that defines an example group with the provided
1128
+ # metadata. Can be used to define example group/metadata shortcuts.
1129
+ #
1130
+ # @example
1131
+ # RSpec.configure do |config|
1132
+ # config.alias_example_group_to :describe_model, :type => :model
1133
+ # end
1134
+ #
1135
+ # shared_context_for "model tests", :type => :model do
1136
+ # # define common model test helper methods, `let` declarations, etc
1137
+ # end
1138
+ #
1139
+ # # This lets you do this:
1140
+ #
1141
+ # RSpec.describe_model User do
1142
+ # end
1143
+ #
1144
+ # # ... which is the equivalent of
1145
+ #
1146
+ # RSpec.describe User, :type => :model do
1147
+ # end
1148
+ #
1149
+ # @note The defined aliased will also be added to the top level
1150
+ # (e.g. `main` and from within modules) if
1151
+ # `expose_dsl_globally` is set to true.
1152
+ # @see #alias_example_to
1153
+ # @see #expose_dsl_globally=
1154
+ def alias_example_group_to(new_name, *args)
1155
+ extra_options = Metadata.build_hash_from(args)
1156
+ RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options)
1157
+ end
1158
+
1159
+ # Define an alias for it_should_behave_like that allows different
1160
+ # language (like "it_has_behavior" or "it_behaves_like") to be
1161
+ # employed when including shared examples.
1162
+ #
1163
+ # @example
1164
+ # RSpec.configure do |config|
1165
+ # config.alias_it_behaves_like_to(:it_has_behavior, 'has behavior:')
1166
+ # end
1167
+ #
1168
+ # # allows the user to include a shared example group like:
1169
+ #
1170
+ # describe Entity do
1171
+ # it_has_behavior 'sortability' do
1172
+ # let(:sortable) { Entity.new }
1173
+ # end
1174
+ # end
1175
+ #
1176
+ # # which is reported in the output as:
1177
+ # # Entity
1178
+ # # has behavior: sortability
1179
+ # # ...sortability examples here
1180
+ #
1181
+ # @note Use with caution. This extends the language used in your
1182
+ # specs, but does not add any additional documentation. We use this
1183
+ # in RSpec to define `it_should_behave_like` (for backward
1184
+ # compatibility), but we also add docs for that method.
1185
+ def alias_it_behaves_like_to(new_name, report_label='')
1186
+ RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label)
1187
+ end
1188
+ alias_method :alias_it_should_behave_like_to, :alias_it_behaves_like_to
1189
+
1190
+ # Adds key/value pairs to the `inclusion_filter`. If `args`
1191
+ # includes any symbols that are not part of the hash, each symbol
1192
+ # is treated as a key in the hash with the value `true`.
1193
+ #
1194
+ # ### Note
1195
+ #
1196
+ # Filters set using this method can be overridden from the command line
1197
+ # or config files (e.g. `.rspec`).
1198
+ #
1199
+ # @example
1200
+ # # Given this declaration.
1201
+ # describe "something", :foo => 'bar' do
1202
+ # # ...
1203
+ # end
1204
+ #
1205
+ # # Any of the following will include that group.
1206
+ # config.filter_run_including :foo => 'bar'
1207
+ # config.filter_run_including :foo => /^ba/
1208
+ # config.filter_run_including :foo => lambda {|v| v == 'bar'}
1209
+ # config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
1210
+ #
1211
+ # # Given a proc with an arity of 1, the lambda is passed the value
1212
+ # # related to the key, e.g.
1213
+ # config.filter_run_including :foo => lambda {|v| v == 'bar'}
1214
+ #
1215
+ # # Given a proc with an arity of 2, the lambda is passed the value
1216
+ # # related to the key, and the metadata itself e.g.
1217
+ # config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
1218
+ #
1219
+ # filter_run_including :foo # same as filter_run_including :foo => true
1220
+ def filter_run_including(*args)
1221
+ meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
1222
+ filter_manager.include_with_low_priority meta
1223
+ static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta)
1224
+ end
1225
+ alias_method :filter_run, :filter_run_including
1226
+
1227
+ # Applies the provided filter only if any of examples match, in constrast
1228
+ # to {#filter_run}, which always applies even if no examples match, in
1229
+ # which case no examples will be run. This allows you to leave configured
1230
+ # filters in place that are intended only for temporary use. The most common
1231
+ # example is focus filtering: `config.filter_run_when_matching :focus`.
1232
+ # With that configured, you can temporarily focus an example or group
1233
+ # by tagging it with `:focus` metadata, or prefixing it with an `f`
1234
+ # (as in `fdescribe`, `fcontext` and `fit`) since those are aliases for
1235
+ # `describe`/`context`/`it` with `:focus` metadata.
1236
+ def filter_run_when_matching(*args)
1237
+ when_first_matching_example_defined(*args) do
1238
+ filter_run(*args)
1239
+ end
1240
+ end
1241
+
1242
+ # Clears and reassigns the `inclusion_filter`. Set to `nil` if you don't
1243
+ # want any inclusion filter at all.
1244
+ #
1245
+ # ### Warning
1246
+ #
1247
+ # This overrides any inclusion filters/tags set on the command line or in
1248
+ # configuration files.
1249
+ def inclusion_filter=(filter)
1250
+ meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
1251
+ filter_manager.include_only meta
1252
+ end
1253
+
1254
+ alias_method :filter=, :inclusion_filter=
1255
+
1256
+ # Returns the `inclusion_filter`. If none has been set, returns an empty
1257
+ # hash.
1258
+ def inclusion_filter
1259
+ filter_manager.inclusions
1260
+ end
1261
+
1262
+ alias_method :filter, :inclusion_filter
1263
+
1264
+ # Adds key/value pairs to the `exclusion_filter`. If `args`
1265
+ # includes any symbols that are not part of the hash, each symbol
1266
+ # is treated as a key in the hash with the value `true`.
1267
+ #
1268
+ # ### Note
1269
+ #
1270
+ # Filters set using this method can be overridden from the command line
1271
+ # or config files (e.g. `.rspec`).
1272
+ #
1273
+ # @example
1274
+ # # Given this declaration.
1275
+ # describe "something", :foo => 'bar' do
1276
+ # # ...
1277
+ # end
1278
+ #
1279
+ # # Any of the following will exclude that group.
1280
+ # config.filter_run_excluding :foo => 'bar'
1281
+ # config.filter_run_excluding :foo => /^ba/
1282
+ # config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
1283
+ # config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
1284
+ #
1285
+ # # Given a proc with an arity of 1, the lambda is passed the value
1286
+ # # related to the key, e.g.
1287
+ # config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
1288
+ #
1289
+ # # Given a proc with an arity of 2, the lambda is passed the value
1290
+ # # related to the key, and the metadata itself e.g.
1291
+ # config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
1292
+ #
1293
+ # filter_run_excluding :foo # same as filter_run_excluding :foo => true
1294
+ def filter_run_excluding(*args)
1295
+ meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
1296
+ filter_manager.exclude_with_low_priority meta
1297
+ static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta)
1298
+ end
1299
+
1300
+ # Clears and reassigns the `exclusion_filter`. Set to `nil` if you don't
1301
+ # want any exclusion filter at all.
1302
+ #
1303
+ # ### Warning
1304
+ #
1305
+ # This overrides any exclusion filters/tags set on the command line or in
1306
+ # configuration files.
1307
+ def exclusion_filter=(filter)
1308
+ meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
1309
+ filter_manager.exclude_only meta
1310
+ end
1311
+
1312
+ # Returns the `exclusion_filter`. If none has been set, returns an empty
1313
+ # hash.
1314
+ def exclusion_filter
1315
+ filter_manager.exclusions
1316
+ end
1317
+
1318
+ # Tells RSpec to include `mod` in example groups. Methods defined in
1319
+ # `mod` are exposed to examples (not example groups). Use `filters` to
1320
+ # constrain the groups or examples in which to include the module.
1321
+ #
1322
+ # @example
1323
+ #
1324
+ # module AuthenticationHelpers
1325
+ # def login_as(user)
1326
+ # # ...
1327
+ # end
1328
+ # end
1329
+ #
1330
+ # module UserHelpers
1331
+ # def users(username)
1332
+ # # ...
1333
+ # end
1334
+ # end
1335
+ #
1336
+ # RSpec.configure do |config|
1337
+ # config.include(UserHelpers) # included in all groups
1338
+ # config.include(AuthenticationHelpers, :type => :request)
1339
+ # end
1340
+ #
1341
+ # describe "edit profile", :type => :request do
1342
+ # it "can be viewed by owning user" do
1343
+ # login_as users(:jdoe)
1344
+ # get "/profiles/jdoe"
1345
+ # assert_select ".username", :text => 'jdoe'
1346
+ # end
1347
+ # end
1348
+ #
1349
+ # @note Filtered module inclusions can also be applied to
1350
+ # individual examples that have matching metadata. Just like
1351
+ # Ruby's object model is that every object has a singleton class
1352
+ # which has only a single instance, RSpec's model is that every
1353
+ # example has a singleton example group containing just the one
1354
+ # example.
1355
+ #
1356
+ # @see #include_context
1357
+ # @see #extend
1358
+ # @see #prepend
1359
+ def include(mod, *filters)
1360
+ define_mixed_in_module(mod, filters, @include_modules, :include) do |group|
1361
+ safe_include(mod, group)
1362
+ end
1363
+ end
1364
+
1365
+ # Tells RSpec to include the named shared example group in example groups.
1366
+ # Use `filters` to constrain the groups or examples in which to include
1367
+ # the example group.
1368
+ #
1369
+ # @example
1370
+ #
1371
+ # RSpec.shared_context "example users" do
1372
+ # let(:admin_user) { create_user(:admin) }
1373
+ # let(:guest_user) { create_user(:guest) }
1374
+ # end
1375
+ #
1376
+ # RSpec.configure do |config|
1377
+ # config.include_context "example users", :type => :request
1378
+ # end
1379
+ #
1380
+ # RSpec.describe "The admin page", :type => :request do
1381
+ # it "can be viewed by admins" do
1382
+ # login_with admin_user
1383
+ # get "/admin"
1384
+ # expect(response).to be_ok
1385
+ # end
1386
+ #
1387
+ # it "cannot be viewed by guests" do
1388
+ # login_with guest_user
1389
+ # get "/admin"
1390
+ # expect(response).to be_forbidden
1391
+ # end
1392
+ # end
1393
+ #
1394
+ # @note Filtered context inclusions can also be applied to
1395
+ # individual examples that have matching metadata. Just like
1396
+ # Ruby's object model is that every object has a singleton class
1397
+ # which has only a single instance, RSpec's model is that every
1398
+ # example has a singleton example group containing just the one
1399
+ # example.
1400
+ #
1401
+ # @see #include
1402
+ def include_context(shared_group_name, *filters)
1403
+ shared_module = world.shared_example_group_registry.find([:main], shared_group_name)
1404
+ include shared_module, *filters
1405
+ end
1406
+
1407
+ # Tells RSpec to extend example groups with `mod`. Methods defined in
1408
+ # `mod` are exposed to example groups (not examples). Use `filters` to
1409
+ # constrain the groups to extend.
1410
+ #
1411
+ # Similar to `include`, but behavior is added to example groups, which
1412
+ # are classes, rather than the examples, which are instances of those
1413
+ # classes.
1414
+ #
1415
+ # @example
1416
+ #
1417
+ # module UiHelpers
1418
+ # def run_in_browser
1419
+ # # ...
1420
+ # end
1421
+ # end
1422
+ #
1423
+ # RSpec.configure do |config|
1424
+ # config.extend(UiHelpers, :type => :request)
1425
+ # end
1426
+ #
1427
+ # describe "edit profile", :type => :request do
1428
+ # run_in_browser
1429
+ #
1430
+ # it "does stuff in the client" do
1431
+ # # ...
1432
+ # end
1433
+ # end
1434
+ #
1435
+ # @see #include
1436
+ # @see #prepend
1437
+ def extend(mod, *filters)
1438
+ define_mixed_in_module(mod, filters, @extend_modules, :extend) do |group|
1439
+ safe_extend(mod, group)
1440
+ end
1441
+ end
1442
+
1443
+ if RSpec::Support::RubyFeatures.module_prepends_supported?
1444
+ # Tells RSpec to prepend example groups with `mod`. Methods defined in
1445
+ # `mod` are exposed to examples (not example groups). Use `filters` to
1446
+ # constrain the groups in which to prepend the module.
1447
+ #
1448
+ # Similar to `include`, but module is included before the example group's class
1449
+ # in the ancestor chain.
1450
+ #
1451
+ # @example
1452
+ #
1453
+ # module OverrideMod
1454
+ # def override_me
1455
+ # "overridden"
1456
+ # end
1457
+ # end
1458
+ #
1459
+ # RSpec.configure do |config|
1460
+ # config.prepend(OverrideMod, :method => :prepend)
1461
+ # end
1462
+ #
1463
+ # describe "overriding example's class", :method => :prepend do
1464
+ # it "finds the user" do
1465
+ # self.class.class_eval do
1466
+ # def override_me
1467
+ # end
1468
+ # end
1469
+ # override_me # => "overridden"
1470
+ # # ...
1471
+ # end
1472
+ # end
1473
+ #
1474
+ # @see #include
1475
+ # @see #extend
1476
+ def prepend(mod, *filters)
1477
+ define_mixed_in_module(mod, filters, @prepend_modules, :prepend) do |group|
1478
+ safe_prepend(mod, group)
1479
+ end
1480
+ end
1481
+ end
1482
+
1483
+ # @private
1484
+ #
1485
+ # Used internally to extend a group with modules using `include`, `prepend` and/or
1486
+ # `extend`.
1487
+ def configure_group(group)
1488
+ group.hooks.register_globals(group, hooks)
1489
+
1490
+ configure_group_with group, @include_modules, :safe_include
1491
+ configure_group_with group, @extend_modules, :safe_extend
1492
+ configure_group_with group, @prepend_modules, :safe_prepend
1493
+ end
1494
+
1495
+ # @private
1496
+ #
1497
+ # Used internally to extend the singleton class of a single example's
1498
+ # example group instance with modules using `include` and/or `extend`.
1499
+ def configure_example(example, example_hooks)
1500
+ example_hooks.register_global_singleton_context_hooks(example, hooks)
1501
+ singleton_group = example.example_group_instance.singleton_class
1502
+
1503
+ # We replace the metadata so that SharedExampleGroupModule#included
1504
+ # has access to the example's metadata[:location].
1505
+ singleton_group.with_replaced_metadata(example.metadata) do
1506
+ modules = @include_modules.items_for(example.metadata)
1507
+ modules.each do |mod|
1508
+ safe_include(mod, example.example_group_instance.singleton_class)
1509
+ end
1510
+
1511
+ MemoizedHelpers.define_helpers_on(singleton_group) unless modules.empty?
1512
+ end
1513
+ end
1514
+
1515
+ # @private
1516
+ def requires=(paths)
1517
+ directories = ['lib', default_path].select { |p| File.directory? p }
1518
+ RSpec::Core::RubyProject.add_to_load_path(*directories)
1519
+ paths.each { |path| load_file_handling_errors(:require, path) }
1520
+ @requires += paths
1521
+ end
1522
+
1523
+ # @private
1524
+ def in_project_source_dir_regex
1525
+ regexes = project_source_dirs.map do |dir|
1526
+ /\A#{Regexp.escape(File.expand_path(dir))}\//
1527
+ end
1528
+
1529
+ Regexp.union(regexes)
1530
+ end
1531
+
1532
+ # @private
1533
+ def configure_mock_framework
1534
+ RSpec::Core::ExampleGroup.__send__(:include, mock_framework)
1535
+ conditionally_disable_mocks_monkey_patching
1536
+ end
1537
+
1538
+ # @private
1539
+ def configure_expectation_framework
1540
+ expectation_frameworks.each do |framework|
1541
+ RSpec::Core::ExampleGroup.__send__(:include, framework)
1542
+ end
1543
+ conditionally_disable_expectations_monkey_patching
1544
+ end
1545
+
1546
+ # @private
1547
+ def load_spec_files
1548
+ # Note which spec files world is already aware of.
1549
+ # This is generally only needed for when the user runs
1550
+ # `ruby path/to/spec.rb` (and loads `rspec/autorun`) --
1551
+ # in that case, the spec file was loaded by `ruby` and
1552
+ # isn't loaded by us here so we only know about it because
1553
+ # of an example group being registered in it.
1554
+ world.registered_example_group_files.each do |f|
1555
+ loaded_spec_files << f # the registered files are already expended absolute paths
1556
+ end
1557
+
1558
+ files_to_run.uniq.each do |f|
1559
+ file = File.expand_path(f)
1560
+ load_file_handling_errors(:load, file)
1561
+ loaded_spec_files << file
1562
+ end
1563
+
1564
+ @spec_files_loaded = true
1565
+ end
1566
+
1567
+ # @private
1568
+ DEFAULT_FORMATTER = lambda { |string| string }
1569
+
1570
+ # Formats the docstring output using the block provided.
1571
+ #
1572
+ # @example
1573
+ # # This will strip the descriptions of both examples and example
1574
+ # # groups.
1575
+ # RSpec.configure do |config|
1576
+ # config.format_docstrings { |s| s.strip }
1577
+ # end
1578
+ def format_docstrings(&block)
1579
+ @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER
1580
+ end
1581
+
1582
+ # @private
1583
+ def format_docstrings_block
1584
+ @format_docstrings_block ||= DEFAULT_FORMATTER
1585
+ end
1586
+
1587
+ # @private
1588
+ def self.delegate_to_ordering_manager(*methods)
1589
+ methods.each do |method|
1590
+ define_method method do |*args, &block|
1591
+ ordering_manager.__send__(method, *args, &block)
1592
+ end
1593
+ end
1594
+ end
1595
+
1596
+ # @!method seed=(value)
1597
+ #
1598
+ # Sets the seed value and sets the default global ordering to random.
1599
+ delegate_to_ordering_manager :seed=
1600
+
1601
+ # @!method seed
1602
+ # Seed for random ordering (default: generated randomly each run).
1603
+ #
1604
+ # When you run specs with `--order random`, RSpec generates a random seed
1605
+ # for the randomization and prints it to the `output_stream` (assuming
1606
+ # you're using RSpec's built-in formatters). If you discover an ordering
1607
+ # dependency (i.e. examples fail intermittently depending on order), set
1608
+ # this (on Configuration or on the command line with `--seed`) to run
1609
+ # using the same seed while you debug the issue.
1610
+ #
1611
+ # We recommend, actually, that you use the command line approach so you
1612
+ # don't accidentally leave the seed encoded.
1613
+ delegate_to_ordering_manager :seed
1614
+
1615
+ # @!method order=(value)
1616
+ #
1617
+ # Sets the default global ordering strategy. By default this can be one
1618
+ # of `:defined`, `:random`, but is customizable through the
1619
+ # `register_ordering` API. If order is set to `'rand:<seed>'`,
1620
+ # the seed will also be set.
1621
+ #
1622
+ # @see #register_ordering
1623
+ delegate_to_ordering_manager :order=
1624
+
1625
+ # @!method register_ordering(name)
1626
+ #
1627
+ # Registers a named ordering strategy that can later be
1628
+ # used to order an example group's subgroups by adding
1629
+ # `:order => <name>` metadata to the example group.
1630
+ #
1631
+ # @param name [Symbol] The name of the ordering.
1632
+ # @yield Block that will order the given examples or example groups
1633
+ # @yieldparam list [Array<RSpec::Core::Example>,
1634
+ # Array<RSpec::Core::ExampleGroup>] The examples or groups to order
1635
+ # @yieldreturn [Array<RSpec::Core::Example>,
1636
+ # Array<RSpec::Core::ExampleGroup>] The re-ordered examples or groups
1637
+ #
1638
+ # @example
1639
+ # RSpec.configure do |rspec|
1640
+ # rspec.register_ordering :reverse do |list|
1641
+ # list.reverse
1642
+ # end
1643
+ # end
1644
+ #
1645
+ # RSpec.describe 'MyClass', :order => :reverse do
1646
+ # # ...
1647
+ # end
1648
+ #
1649
+ # @note Pass the symbol `:global` to set the ordering strategy that
1650
+ # will be used to order the top-level example groups and any example
1651
+ # groups that do not have declared `:order` metadata.
1652
+ #
1653
+ # @example
1654
+ # RSpec.configure do |rspec|
1655
+ # rspec.register_ordering :global do |examples|
1656
+ # acceptance, other = examples.partition do |example|
1657
+ # example.metadata[:type] == :acceptance
1658
+ # end
1659
+ # other + acceptance
1660
+ # end
1661
+ # end
1662
+ #
1663
+ # RSpec.describe 'MyClass', :type => :acceptance do
1664
+ # # will run last
1665
+ # end
1666
+ #
1667
+ # RSpec.describe 'MyClass' do
1668
+ # # will run first
1669
+ # end
1670
+ #
1671
+ delegate_to_ordering_manager :register_ordering
1672
+
1673
+ # @private
1674
+ delegate_to_ordering_manager :seed_used?, :ordering_registry
1675
+
1676
+ # Set Ruby warnings on or off.
1677
+ def warnings=(value)
1678
+ $VERBOSE = !!value
1679
+ end
1680
+
1681
+ # @return [Boolean] Whether or not ruby warnings are enabled.
1682
+ def warnings?
1683
+ $VERBOSE
1684
+ end
1685
+
1686
+ # @private
1687
+ RAISE_ERROR_WARNING_NOTIFIER = lambda { |message| raise message }
1688
+
1689
+ # Turns warnings into errors. This can be useful when
1690
+ # you want RSpec to run in a 'strict' no warning situation.
1691
+ #
1692
+ # @example
1693
+ #
1694
+ # RSpec.configure do |rspec|
1695
+ # rspec.raise_on_warning = true
1696
+ # end
1697
+ def raise_on_warning=(value)
1698
+ if value
1699
+ RSpec::Support.warning_notifier = RAISE_ERROR_WARNING_NOTIFIER
1700
+ else
1701
+ RSpec::Support.warning_notifier = RSpec::Support::DEFAULT_WARNING_NOTIFIER
1702
+ end
1703
+ end
1704
+
1705
+ # Exposes the current running example via the named
1706
+ # helper method. RSpec 2.x exposed this via `example`,
1707
+ # but in RSpec 3.0, the example is instead exposed via
1708
+ # an arg yielded to `it`, `before`, `let`, etc. However,
1709
+ # some extension gems (such as Capybara) depend on the
1710
+ # RSpec 2.x's `example` method, so this config option
1711
+ # can be used to maintain compatibility.
1712
+ #
1713
+ # @param method_name [Symbol] the name of the helper method
1714
+ #
1715
+ # @example
1716
+ #
1717
+ # RSpec.configure do |rspec|
1718
+ # rspec.expose_current_running_example_as :example
1719
+ # end
1720
+ #
1721
+ # describe MyClass do
1722
+ # before do
1723
+ # # `example` can be used here because of the above config.
1724
+ # do_something if example.metadata[:type] == "foo"
1725
+ # end
1726
+ # end
1727
+ def expose_current_running_example_as(method_name)
1728
+ ExposeCurrentExample.module_exec do
1729
+ extend RSpec::SharedContext
1730
+ let(method_name) { |ex| ex }
1731
+ end
1732
+
1733
+ include ExposeCurrentExample
1734
+ end
1735
+
1736
+ # @private
1737
+ module ExposeCurrentExample; end
1738
+
1739
+ # Turns deprecation warnings into errors, in order to surface
1740
+ # the full backtrace of the call site. This can be useful when
1741
+ # you need more context to address a deprecation than the
1742
+ # single-line call site normally provided.
1743
+ #
1744
+ # @example
1745
+ #
1746
+ # RSpec.configure do |rspec|
1747
+ # rspec.raise_errors_for_deprecations!
1748
+ # end
1749
+ def raise_errors_for_deprecations!
1750
+ self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new
1751
+ end
1752
+
1753
+ # Enables zero monkey patching mode for RSpec. It removes monkey
1754
+ # patching of the top-level DSL methods (`describe`,
1755
+ # `shared_examples_for`, etc) onto `main` and `Module`, instead
1756
+ # requiring you to prefix these methods with `RSpec.`. It enables
1757
+ # expect-only syntax for rspec-mocks and rspec-expectations. It
1758
+ # simply disables monkey patching on whatever pieces of RSpec
1759
+ # the user is using.
1760
+ #
1761
+ # @note It configures rspec-mocks and rspec-expectations only
1762
+ # if the user is using those (either explicitly or implicitly
1763
+ # by not setting `mock_with` or `expect_with` to anything else).
1764
+ #
1765
+ # @note If the user uses this options with `mock_with :mocha`
1766
+ # (or similiar) they will still have monkey patching active
1767
+ # in their test environment from mocha.
1768
+ #
1769
+ # @example
1770
+ #
1771
+ # # It disables all monkey patching.
1772
+ # RSpec.configure do |config|
1773
+ # config.disable_monkey_patching!
1774
+ # end
1775
+ #
1776
+ # # Is an equivalent to
1777
+ # RSpec.configure do |config|
1778
+ # config.expose_dsl_globally = false
1779
+ #
1780
+ # config.mock_with :rspec do |mocks|
1781
+ # mocks.syntax = :expect
1782
+ # mocks.patch_marshal_to_support_partial_doubles = false
1783
+ # end
1784
+ #
1785
+ # config.expect_with :rspec do |expectations|
1786
+ # expectations.syntax = :expect
1787
+ # end
1788
+ # end
1789
+ def disable_monkey_patching!
1790
+ self.expose_dsl_globally = false
1791
+ self.disable_monkey_patching = true
1792
+ conditionally_disable_mocks_monkey_patching
1793
+ conditionally_disable_expectations_monkey_patching
1794
+ end
1795
+
1796
+ # @private
1797
+ attr_accessor :disable_monkey_patching
1798
+
1799
+ # Defines a callback that can assign derived metadata values.
1800
+ #
1801
+ # @param filters [Array<Symbol>, Hash] metadata filters that determine
1802
+ # which example or group metadata hashes the callback will be triggered
1803
+ # for. If none are given, the callback will be run against the metadata
1804
+ # hashes of all groups and examples.
1805
+ # @yieldparam metadata [Hash] original metadata hash from an example or
1806
+ # group. Mutate this in your block as needed.
1807
+ #
1808
+ # @example
1809
+ # RSpec.configure do |config|
1810
+ # # Tag all groups and examples in the spec/unit directory with
1811
+ # # :type => :unit
1812
+ # config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata|
1813
+ # metadata[:type] = :unit
1814
+ # end
1815
+ # end
1816
+ def define_derived_metadata(*filters, &block)
1817
+ meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
1818
+ @derived_metadata_blocks.append(block, meta)
1819
+ end
1820
+
1821
+ # Defines a callback that runs after the first example with matching
1822
+ # metadata is defined. If no examples are defined with matching metadata,
1823
+ # it will not get called at all.
1824
+ #
1825
+ # This can be used to ensure some setup is performed (such as bootstrapping
1826
+ # a DB or loading a specific file that adds significantly to the boot time)
1827
+ # if needed (as indicated by the presence of an example with matching metadata)
1828
+ # but avoided otherwise.
1829
+ #
1830
+ # @example
1831
+ # RSpec.configure do |config|
1832
+ # config.when_first_matching_example_defined(:db) do
1833
+ # # Load a support file that does some heavyweight setup,
1834
+ # # including bootstrapping the DB, but only if we have loaded
1835
+ # # any examples tagged with `:db`.
1836
+ # require 'support/db'
1837
+ # end
1838
+ # end
1839
+ def when_first_matching_example_defined(*filters)
1840
+ specified_meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
1841
+
1842
+ callback = lambda do |example_or_group_meta|
1843
+ # Example groups do not have `:example_group` metadata
1844
+ # (instead they have `:parent_example_group` metadata).
1845
+ return unless example_or_group_meta.key?(:example_group)
1846
+
1847
+ # Ensure the callback only fires once.
1848
+ @derived_metadata_blocks.delete(callback, specified_meta)
1849
+
1850
+ yield
1851
+ end
1852
+
1853
+ @derived_metadata_blocks.append(callback, specified_meta)
1854
+ end
1855
+
1856
+ # @private
1857
+ def apply_derived_metadata_to(metadata)
1858
+ already_run_blocks = Set.new
1859
+
1860
+ # We loop and attempt to re-apply metadata blocks to support cascades
1861
+ # (e.g. where a derived bit of metadata triggers the application of
1862
+ # another piece of derived metadata, etc)
1863
+ #
1864
+ # We limit our looping to 200 times as a way to detect infinitely recursing derived metadata blocks.
1865
+ # It's hard to imagine a valid use case for a derived metadata cascade greater than 200 iterations.
1866
+ 200.times do
1867
+ return if @derived_metadata_blocks.items_for(metadata).all? do |block|
1868
+ already_run_blocks.include?(block).tap do |skip_block|
1869
+ block.call(metadata) unless skip_block
1870
+ already_run_blocks << block
1871
+ end
1872
+ end
1873
+ end
1874
+
1875
+ # If we got here, then `@derived_metadata_blocks.items_for(metadata).all?` never returned
1876
+ # `true` above and we treat this as an attempt to recurse infinitely. It's better to fail
1877
+ # with a clear # error than hang indefinitely, which is what would happen if we didn't limit
1878
+ # the looping above.
1879
+ raise SystemStackError, "Attempted to recursively derive metadata indefinitely."
1880
+ end
1881
+
1882
+ # Defines a `before` hook. See {Hooks#before} for full docs.
1883
+ #
1884
+ # This method differs from {Hooks#before} in only one way: it supports
1885
+ # the `:suite` scope. Hooks with the `:suite` scope will be run once before
1886
+ # the first example of the entire suite is executed.
1887
+ #
1888
+ # @see #prepend_before
1889
+ # @see #after
1890
+ # @see #append_after
1891
+ def before(scope=nil, *meta, &block)
1892
+ handle_suite_hook(scope, meta) do
1893
+ @before_suite_hooks << Hooks::BeforeHook.new(block, {})
1894
+ end || begin
1895
+ # defeat Ruby 2.5 lazy proc allocation to ensure
1896
+ # the methods below are passed the same proc instances
1897
+ # so `Hook` equality is preserved. For more info, see:
1898
+ # https://bugs.ruby-lang.org/issues/14045#note-5
1899
+ block.__id__
1900
+
1901
+ add_hook_to_existing_matching_groups(meta, scope) { |g| g.before(scope, *meta, &block) }
1902
+ super(scope, *meta, &block)
1903
+ end
1904
+ end
1905
+ alias_method :append_before, :before
1906
+
1907
+ # Adds `block` to the start of the list of `before` blocks in the same
1908
+ # scope (`:example`, `:context`, or `:suite`), in contrast to {#before},
1909
+ # which adds the hook to the end of the list.
1910
+ #
1911
+ # See {Hooks#before} for full `before` hook docs.
1912
+ #
1913
+ # This method differs from {Hooks#prepend_before} in only one way: it supports
1914
+ # the `:suite` scope. Hooks with the `:suite` scope will be run once before
1915
+ # the first example of the entire suite is executed.
1916
+ #
1917
+ # @see #before
1918
+ # @see #after
1919
+ # @see #append_after
1920
+ def prepend_before(scope=nil, *meta, &block)
1921
+ handle_suite_hook(scope, meta) do
1922
+ @before_suite_hooks.unshift Hooks::BeforeHook.new(block, {})
1923
+ end || begin
1924
+ # defeat Ruby 2.5 lazy proc allocation to ensure
1925
+ # the methods below are passed the same proc instances
1926
+ # so `Hook` equality is preserved. For more info, see:
1927
+ # https://bugs.ruby-lang.org/issues/14045#note-5
1928
+ block.__id__
1929
+
1930
+ add_hook_to_existing_matching_groups(meta, scope) { |g| g.prepend_before(scope, *meta, &block) }
1931
+ super(scope, *meta, &block)
1932
+ end
1933
+ end
1934
+
1935
+ # Defines a `after` hook. See {Hooks#after} for full docs.
1936
+ #
1937
+ # This method differs from {Hooks#after} in only one way: it supports
1938
+ # the `:suite` scope. Hooks with the `:suite` scope will be run once after
1939
+ # the last example of the entire suite is executed.
1940
+ #
1941
+ # @see #append_after
1942
+ # @see #before
1943
+ # @see #prepend_before
1944
+ def after(scope=nil, *meta, &block)
1945
+ handle_suite_hook(scope, meta) do
1946
+ @after_suite_hooks.unshift Hooks::AfterHook.new(block, {})
1947
+ end || begin
1948
+ # defeat Ruby 2.5 lazy proc allocation to ensure
1949
+ # the methods below are passed the same proc instances
1950
+ # so `Hook` equality is preserved. For more info, see:
1951
+ # https://bugs.ruby-lang.org/issues/14045#note-5
1952
+ block.__id__
1953
+
1954
+ add_hook_to_existing_matching_groups(meta, scope) { |g| g.after(scope, *meta, &block) }
1955
+ super(scope, *meta, &block)
1956
+ end
1957
+ end
1958
+ alias_method :prepend_after, :after
1959
+
1960
+ # Adds `block` to the end of the list of `after` blocks in the same
1961
+ # scope (`:example`, `:context`, or `:suite`), in contrast to {#after},
1962
+ # which adds the hook to the start of the list.
1963
+ #
1964
+ # See {Hooks#after} for full `after` hook docs.
1965
+ #
1966
+ # This method differs from {Hooks#append_after} in only one way: it supports
1967
+ # the `:suite` scope. Hooks with the `:suite` scope will be run once after
1968
+ # the last example of the entire suite is executed.
1969
+ #
1970
+ # @see #append_after
1971
+ # @see #before
1972
+ # @see #prepend_before
1973
+ def append_after(scope=nil, *meta, &block)
1974
+ handle_suite_hook(scope, meta) do
1975
+ @after_suite_hooks << Hooks::AfterHook.new(block, {})
1976
+ end || begin
1977
+ # defeat Ruby 2.5 lazy proc allocation to ensure
1978
+ # the methods below are passed the same proc instances
1979
+ # so `Hook` equality is preserved. For more info, see:
1980
+ # https://bugs.ruby-lang.org/issues/14045#note-5
1981
+ block.__id__
1982
+
1983
+ add_hook_to_existing_matching_groups(meta, scope) { |g| g.append_after(scope, *meta, &block) }
1984
+ super(scope, *meta, &block)
1985
+ end
1986
+ end
1987
+
1988
+ # Registers `block` as an `around` hook.
1989
+ #
1990
+ # See {Hooks#around} for full `around` hook docs.
1991
+ def around(scope=nil, *meta, &block)
1992
+ # defeat Ruby 2.5 lazy proc allocation to ensure
1993
+ # the methods below are passed the same proc instances
1994
+ # so `Hook` equality is preserved. For more info, see:
1995
+ # https://bugs.ruby-lang.org/issues/14045#note-5
1996
+ block.__id__
1997
+
1998
+ add_hook_to_existing_matching_groups(meta, scope) { |g| g.around(scope, *meta, &block) }
1999
+ super(scope, *meta, &block)
2000
+ end
2001
+
2002
+ # @private
2003
+ def with_suite_hooks
2004
+ return yield if dry_run?
2005
+
2006
+ begin
2007
+ run_suite_hooks("a `before(:suite)` hook", @before_suite_hooks)
2008
+ yield
2009
+ ensure
2010
+ run_suite_hooks("an `after(:suite)` hook", @after_suite_hooks)
2011
+ end
2012
+ end
2013
+
2014
+ # @private
2015
+ # Holds the various registered hooks. Here we use a FilterableItemRepository
2016
+ # implementation that is specifically optimized for the read/write patterns
2017
+ # of the config object.
2018
+ def hooks
2019
+ @hooks ||= HookCollections.new(self, FilterableItemRepository::QueryOptimized)
2020
+ end
2021
+
2022
+ # Invokes block before defining an example group
2023
+ def on_example_group_definition(&block)
2024
+ on_example_group_definition_callbacks << block
2025
+ end
2026
+
2027
+ # @api private
2028
+ # Returns an array of blocks to call before defining an example group
2029
+ def on_example_group_definition_callbacks
2030
+ @on_example_group_definition_callbacks ||= []
2031
+ end
2032
+
2033
+ # @private
2034
+ def bisect_runner_class
2035
+ @bisect_runner_class ||= begin
2036
+ case bisect_runner
2037
+ when :fork
2038
+ RSpec::Support.require_rspec_core 'bisect/fork_runner'
2039
+ Bisect::ForkRunner
2040
+ when :shell
2041
+ RSpec::Support.require_rspec_core 'bisect/shell_runner'
2042
+ Bisect::ShellRunner
2043
+ else
2044
+ raise "Unsupported value for `bisect_runner` (#{bisect_runner.inspect}). " \
2045
+ "Only `:fork` and `:shell` are supported."
2046
+ end
2047
+ end
2048
+ end
2049
+
2050
+ private
2051
+
2052
+ def load_file_handling_errors(method, file)
2053
+ __send__(method, file)
2054
+ rescue Support::AllExceptionsExceptOnesWeMustNotRescue => ex
2055
+ relative_file = Metadata.relative_path(file)
2056
+ reporter.notify_non_example_exception(ex, "An error occurred while loading #{relative_file}.")
2057
+ RSpec.world.wants_to_quit = true
2058
+ end
2059
+
2060
+ def handle_suite_hook(scope, meta)
2061
+ return nil unless scope == :suite
2062
+
2063
+ unless meta.empty?
2064
+ # TODO: in RSpec 4, consider raising an error here.
2065
+ # We warn only for backwards compatibility.
2066
+ RSpec.warn_with "WARNING: `:suite` hooks do not support metadata since " \
2067
+ "they apply to the suite as a whole rather than " \
2068
+ "any individual example or example group that has metadata. " \
2069
+ "The metadata you have provided (#{meta.inspect}) will be ignored."
2070
+ end
2071
+
2072
+ yield
2073
+ end
2074
+
2075
+ def run_suite_hooks(hook_description, hooks)
2076
+ context = SuiteHookContext.new(hook_description, reporter)
2077
+
2078
+ hooks.each do |hook|
2079
+ begin
2080
+ hook.run(context)
2081
+ rescue Support::AllExceptionsExceptOnesWeMustNotRescue => ex
2082
+ context.set_exception(ex)
2083
+
2084
+ # Do not run subsequent `before` hooks if one fails.
2085
+ # But for `after` hooks, we run them all so that all
2086
+ # cleanup bits get a chance to complete, minimizing the
2087
+ # chance that resources get left behind.
2088
+ break if hooks.equal?(@before_suite_hooks)
2089
+ end
2090
+ end
2091
+ end
2092
+
2093
+ def get_files_to_run(paths)
2094
+ files = FlatMap.flat_map(paths_to_check(paths)) do |path|
2095
+ path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
2096
+ File.directory?(path) ? gather_directories(path) : extract_location(path)
2097
+ end.uniq
2098
+
2099
+ return files unless only_failures?
2100
+ relative_files = files.map { |f| Metadata.relative_path(File.expand_path f) }
2101
+ intersection = (relative_files & spec_files_with_failures.to_a)
2102
+ intersection.empty? ? files : intersection
2103
+ end
2104
+
2105
+ def paths_to_check(paths)
2106
+ return paths if pattern_might_load_specs_from_vendored_dirs?
2107
+ paths + [Dir.getwd]
2108
+ end
2109
+
2110
+ def pattern_might_load_specs_from_vendored_dirs?
2111
+ pattern.split(File::SEPARATOR).first.include?('**')
2112
+ end
2113
+
2114
+ def gather_directories(path)
2115
+ include_files = get_matching_files(path, pattern)
2116
+ exclude_files = get_matching_files(path, exclude_pattern)
2117
+ (include_files - exclude_files).uniq
2118
+ end
2119
+
2120
+ def get_matching_files(path, pattern)
2121
+ raw_files = Dir[file_glob_from(path, pattern)]
2122
+ raw_files.map { |file| File.expand_path(file) }.sort
2123
+ end
2124
+
2125
+ def file_glob_from(path, pattern)
2126
+ stripped = "{#{pattern.gsub(/\s*,\s*/, ',')}}"
2127
+ return stripped if pattern =~ /^(\.\/)?#{Regexp.escape path}/ || absolute_pattern?(pattern)
2128
+ File.join(path, stripped)
2129
+ end
2130
+
2131
+ if RSpec::Support::OS.windows?
2132
+ # :nocov:
2133
+ def absolute_pattern?(pattern)
2134
+ pattern =~ /\A[A-Z]:\\/ || windows_absolute_network_path?(pattern)
2135
+ end
2136
+
2137
+ def windows_absolute_network_path?(pattern)
2138
+ return false unless ::File::ALT_SEPARATOR
2139
+ pattern.start_with?(::File::ALT_SEPARATOR + ::File::ALT_SEPARATOR)
2140
+ end
2141
+ # :nocov:
2142
+ else
2143
+ def absolute_pattern?(pattern)
2144
+ pattern.start_with?(File::Separator)
2145
+ end
2146
+ end
2147
+
2148
+ def extract_location(path)
2149
+ match = /^(.*?)((?:\:\d+)+)$/.match(path)
2150
+
2151
+ if match
2152
+ captures = match.captures
2153
+ path = captures[0]
2154
+ lines = captures[1][1..-1].split(":").map(&:to_i)
2155
+ filter_manager.add_location path, lines
2156
+ else
2157
+ path, scoped_ids = Example.parse_id(path)
2158
+ filter_manager.add_ids(path, scoped_ids.split(/\s*,\s*/)) if scoped_ids
2159
+ end
2160
+
2161
+ return [] if path == default_path
2162
+ File.expand_path(path)
2163
+ end
2164
+
2165
+ def command
2166
+ $0.split(File::SEPARATOR).last
2167
+ end
2168
+
2169
+ def value_for(key)
2170
+ @preferred_options.fetch(key) { yield }
2171
+ end
2172
+
2173
+ def define_built_in_hooks
2174
+ around(:example, :aggregate_failures => true) do |procsy|
2175
+ begin
2176
+ aggregate_failures(nil, :hide_backtrace => true, &procsy)
2177
+ rescue Support::AllExceptionsExceptOnesWeMustNotRescue => exception
2178
+ procsy.example.set_aggregate_failures_exception(exception)
2179
+ end
2180
+ end
2181
+ end
2182
+
2183
+ def assert_no_example_groups_defined(config_option)
2184
+ return unless world.example_groups.any?
2185
+
2186
+ raise MustBeConfiguredBeforeExampleGroupsError.new(
2187
+ "RSpec's #{config_option} configuration option must be configured before " \
2188
+ "any example groups are defined, but you have already defined a group."
2189
+ )
2190
+ end
2191
+
2192
+ def output_wrapper
2193
+ @output_wrapper ||= OutputWrapper.new(output_stream)
2194
+ end
2195
+
2196
+ def output_to_tty?(output=output_stream)
2197
+ output.respond_to?(:tty?) && output.tty?
2198
+ end
2199
+
2200
+ def conditionally_disable_mocks_monkey_patching
2201
+ return unless disable_monkey_patching && rspec_mocks_loaded?
2202
+
2203
+ RSpec::Mocks.configuration.tap do |config|
2204
+ config.syntax = :expect
2205
+ config.patch_marshal_to_support_partial_doubles = false
2206
+ end
2207
+ end
2208
+
2209
+ def conditionally_disable_expectations_monkey_patching
2210
+ return unless disable_monkey_patching && rspec_expectations_loaded?
2211
+
2212
+ RSpec::Expectations.configuration.syntax = :expect
2213
+ end
2214
+
2215
+ def rspec_mocks_loaded?
2216
+ defined?(RSpec::Mocks.configuration)
2217
+ end
2218
+
2219
+ def rspec_expectations_loaded?
2220
+ defined?(RSpec::Expectations.configuration)
2221
+ end
2222
+
2223
+ def update_pattern_attr(name, value)
2224
+ if @spec_files_loaded
2225
+ RSpec.warning "Configuring `#{name}` to #{value} has no effect since " \
2226
+ "RSpec has already loaded the spec files."
2227
+ end
2228
+
2229
+ instance_variable_set(:"@#{name}", value)
2230
+ @files_to_run = nil
2231
+ end
2232
+
2233
+ def clear_values_derived_from_example_status_persistence_file_path
2234
+ @last_run_statuses = nil
2235
+ @spec_files_with_failures = nil
2236
+ end
2237
+
2238
+ def configure_group_with(group, module_list, application_method)
2239
+ module_list.items_for(group.metadata).each do |mod|
2240
+ __send__(application_method, mod, group)
2241
+ end
2242
+ end
2243
+
2244
+ def add_hook_to_existing_matching_groups(meta, scope, &block)
2245
+ # For example hooks, we have to apply it to each of the top level
2246
+ # groups, even if the groups do not match. When we apply it, we
2247
+ # apply it with the metadata, so it will only apply to examples
2248
+ # in the group that match the metadata.
2249
+ # #2280 for background and discussion.
2250
+ if scope == :example || scope == :each || scope.nil?
2251
+ world.example_groups.each(&block)
2252
+ else
2253
+ meta = Metadata.build_hash_from(meta.dup)
2254
+ on_existing_matching_groups(meta, &block)
2255
+ end
2256
+ end
2257
+
2258
+ def on_existing_matching_groups(meta)
2259
+ world.traverse_example_group_trees_until do |group|
2260
+ metadata_applies_to_group?(meta, group).tap do |applies|
2261
+ yield group if applies
2262
+ end
2263
+ end
2264
+ end
2265
+
2266
+ def metadata_applies_to_group?(meta, group)
2267
+ meta.empty? || MetadataFilter.apply?(:any?, meta, group.metadata)
2268
+ end
2269
+
2270
+ if RSpec::Support::RubyFeatures.module_prepends_supported?
2271
+ def safe_prepend(mod, host)
2272
+ host.__send__(:prepend, mod) unless host < mod
2273
+ end
2274
+ end
2275
+
2276
+ if RUBY_VERSION.to_f >= 1.9
2277
+ def safe_include(mod, host)
2278
+ host.__send__(:include, mod) unless host < mod
2279
+ end
2280
+
2281
+ def safe_extend(mod, host)
2282
+ host.extend(mod) unless host.singleton_class < mod
2283
+ end
2284
+ else # for 1.8.7
2285
+ # :nocov:
2286
+ def safe_include(mod, host)
2287
+ host.__send__(:include, mod) unless host.included_modules.include?(mod)
2288
+ end
2289
+
2290
+ def safe_extend(mod, host)
2291
+ host.extend(mod) unless (class << host; self; end).included_modules.include?(mod)
2292
+ end
2293
+ # :nocov:
2294
+ end
2295
+
2296
+ def define_mixed_in_module(mod, filters, mod_list, config_method, &block)
2297
+ unless Module === mod
2298
+ raise TypeError, "`RSpec.configuration.#{config_method}` expects a module but got: #{mod.inspect}"
2299
+ end
2300
+
2301
+ meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
2302
+ mod_list.append(mod, meta)
2303
+ on_existing_matching_groups(meta, &block)
2304
+ end
2305
+ end
2306
+ # rubocop:enable Metrics/ClassLength
2307
+ end
2308
+ end