Class: RSpec::Core::Configuration

Inherits:
Object
  • Object
show all
Includes:
Module.new, Hooks
Defined in:
lib/rspec/core/configuration.rb

Overview

Stores runtime configuration information.

Configuration options are loaded from multiple files and joined together with command-line switches and the SPEC_OPTS environment variable.

Precedence order (where later entries overwrite earlier entries on conflicts):

  • Global ($XDG_CONFIG_HOME/rspec/options, or ~/.rspec if it does not exist)
  • Project-specific (./.rspec)
  • Local (./.rspec-local)
  • Command-line options
  • SPEC_OPTS

For example, an option set in the local file will override an option set in your global file.

The global, project-specific and local files can all be overridden with a separate custom file using the --options command-line parameter.

Examples:

Standard settings

RSpec.configure do |c|
  c.drb          = true
  c.drb_port     = 1234
  c.default_path = 'behavior'
end

Hooks

RSpec.configure do |c|
  c.before(:suite)   { establish_connection }
  c.before(:example) {  :authorized }
  c.around(:example) { |ex| Database.transaction(&ex) }
end

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConfiguration

Build an object to store runtime configuration options and set defaults

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/rspec/core/configuration.rb', line 500
def initialize
  # rubocop:disable Style/GlobalVars
  @start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now
  # rubocop:enable Style/GlobalVars
  @expectation_frameworks = []
  @include_modules = FilterableItemRepository::QueryOptimized.new(:any?)
  @extend_modules  = FilterableItemRepository::QueryOptimized.new(:any?)
  @prepend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
  @bisect_runner = RSpec::Support::RubyFeatures.fork_supported? ? :fork : :shell
  @bisect_runner_class = nil
  @before_suite_hooks = []
  @after_suite_hooks  = []
  @mock_framework = nil
  @files_or_directories_to_run = []
  @loaded_spec_files = Set.new
  @color = false
  @color_mode = :automatic
  @pattern = '**{,/*/**}/*_spec.rb'
  @exclude_pattern = ''
  @failure_exit_code = 1
  @fail_if_no_examples = false
  @spec_files_loaded = false
  @backtrace_formatter = BacktraceFormatter.new
  @default_path = 'spec'
  @project_source_dirs = %w[ spec lib app ]
  @deprecation_stream = $stderr
  @output_stream = $stdout
  @reporter = nil
  @reporter_buffer = nil
  @filter_manager = FilterManager.new
  @static_config_filter_manager = FilterManager.new
  @ordering_manager = Ordering::ConfigurationManager.new
  @preferred_options = {}
  @failure_color = :red
  @success_color = :green
  @pending_color = :yellow
  @default_color = :white
  @fixed_color = :blue
  @detail_color = :cyan
  @profile_examples = false
  @requires = []
  @libs = []
  @derived_metadata_blocks = FilterableItemRepository::QueryOptimized.new(:any?)
  @threadsafe = true
  @max_displayed_failure_line_count = 10
  @world = World::Null
  @shared_context_metadata_behavior = :trigger_inclusion
  define_built_in_hooks
end

Instance Attribute Details

#bisect_runnerSymbol

Note:

This option will only be used by --bisect if you set it in a file loaded via --require.

Determines which bisect runner implementation gets used to run subsets of the suite during a bisection. Your choices are:

  • :shell: Performs a spec run by shelling out, booting RSpec and your application environment each time. This runner is the most widely compatible runner, but is not as fast. On platforms that do not support forking, this is the default.
  • :fork: Pre-boots RSpec and your application environment in a parent process, and then forks a child process for each spec run. This runner tends to be significantly faster than the :shell runner but cannot be used in some situations. On platforms that support forking, this is the default. If you use this runner, you should ensure that all of your one-time setup logic goes in a before(:suite) hook instead of getting run at the top-level of a file loaded by --require.

Returns:

  • (Symbol)
472
473
474
# File 'lib/rspec/core/configuration.rb', line 472
def bisect_runner
  @bisect_runner
end

#colorBoolean

Deprecated.

No longer recommended because of complex behavior. Instead, rely on the fact that TTYs will display color by default, or set #color_mode to :on to display color on a non-TTY output.

Enables color output if the output is a TTY. As of RSpec 3.6, this is the default behavior and this option is retained only for backwards compatibility.

Returns:

  • (Boolean)

See Also:

890
891
892
# File 'lib/rspec/core/configuration.rb', line 890
def color
  value_for(:color) { @color }
end

#color_modeBoolean

The mode for determining whether to display output in color. One of:

  • :automatic - the output will be in color if the output is a TTY (the default)
  • :on - the output will be in color, whether or not the output is a TTY
  • :off - the output will not be in color

Returns:

  • (Boolean)

See Also:

903
904
905
# File 'lib/rspec/core/configuration.rb', line 903
def color_mode
  value_for(:color_mode) { @color_mode }
end

#default_colorSymbol

The default output color. Defaults to :white but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

Returns:

  • (Symbol)
350
# File 'lib/rspec/core/configuration.rb', line 350
add_setting :default_color

#default_pathString

Note:

Other scripts invoking rspec indirectly will ignore this setting.

Path to use if no path is provided to the rspec command (default: "spec"). Allows you to just type rspec instead of rspec spec to run all the examples in the spec directory.

Returns:

  • (String)
118
# File 'lib/rspec/core/configuration.rb', line 118
add_read_only_setting :default_path

#detail_colorSymbol

Color used to print details. Defaults to :cyan but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

Returns:

  • (Symbol)
364
# File 'lib/rspec/core/configuration.rb', line 364
add_setting :detail_color

#drbBoolean

Run examples over DRb (default: false). RSpec doesn't supply the DRb server, but you can use tools like spork.

Returns:

  • (Boolean)
128
# File 'lib/rspec/core/configuration.rb', line 128
add_setting :drb

#drb_portvoid

The drb_port (default: nil).

132
# File 'lib/rspec/core/configuration.rb', line 132
add_setting :drb_port

#dry_runvoid

Prints the formatter output of your suite without running any examples or hooks.

236
# File 'lib/rspec/core/configuration.rb', line 236
add_setting :dry_run

#error_streamvoid

Default: $stderr.

136
# File 'lib/rspec/core/configuration.rb', line 136
add_setting :error_stream

#example_status_persistence_file_pathString #example_status_persistence_file_path=(value) ⇒ void

The file path to use for persisting example statuses. Necessary for the --only-failures and --next-failure CLI options.

Overloads:

  • #example_status_persistence_file_pathString

    Returns the file path.

    Returns:

    • (String)

      the file path

  • #example_status_persistence_file_path=(value) ⇒ void

    Parameters:

    • value (String)

      the file path

186
# File 'lib/rspec/core/configuration.rb', line 186
define_reader :example_status_persistence_file_path

#exclude_patternString

Exclude files matching this pattern.

Returns:

  • (String)
293
# File 'lib/rspec/core/configuration.rb', line 293
define_reader :exclude_pattern

#fail_fastvoid

If specified, indicates the number of failures required before cleaning up and exit (default: nil). Can also be true to fail and exit on first failure

209
# File 'lib/rspec/core/configuration.rb', line 209
define_reader :fail_fast

#fail_if_no_examplesBoolean

Whether or not to fail when there are no RSpec examples (default: false).

Returns:

  • (Boolean)
246
# File 'lib/rspec/core/configuration.rb', line 246
add_setting :fail_if_no_examples

#failure_colorSymbol

Color to use to indicate failure. Defaults to :red but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

Returns:

  • (Symbol)
343
# File 'lib/rspec/core/configuration.rb', line 343
add_setting :failure_color

#failure_exit_codeInteger

The exit code to return if there are any failures (default: 1).

Returns:

  • (Integer)
241
# File 'lib/rspec/core/configuration.rb', line 241
add_setting :failure_exit_code

#files_to_runArray

The spec files RSpec will run.

Returns:

  • (Array)

    specified files about to run

1064
1065
1066
# File 'lib/rspec/core/configuration.rb', line 1064
def files_to_run
  @files_to_run ||= get_files_to_run(@files_or_directories_to_run)
end

#fixed_colorSymbol

Color used when a pending example is fixed. Defaults to :blue but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

Returns:

  • (Symbol)
357
# File 'lib/rspec/core/configuration.rb', line 357
add_setting :fixed_color

#libsArray<String>

Returns dirs that have been prepended to the load path by the -I command line option.

Returns:

  • (Array<String>)
257
# File 'lib/rspec/core/configuration.rb', line 257
define_reader :libs

#max_displayed_failure_line_countvoid

Maximum count of failed source lines to display in the failure reports. (default 10). return [Integer]

451
# File 'lib/rspec/core/configuration.rb', line 451
add_setting :max_displayed_failure_line_count

#only_failuresvoid (readonly) Also known as: only_failures?

Indicates if the --only-failures (or --next-failure) flag is being used.

197
# File 'lib/rspec/core/configuration.rb', line 197
define_reader :only_failures

#output_streamIO, String

Determines where RSpec will send its output. Default: $stdout.

Returns:

  • (IO, String)
263
# File 'lib/rspec/core/configuration.rb', line 263
define_reader :output_stream

#patternString

Load files matching this pattern (default: '**{,/*/**}/*_spec.rb').

Returns:

  • (String)
282
# File 'lib/rspec/core/configuration.rb', line 282
define_reader :pattern

#pending_colorSymbol

Color to use to print pending examples. Defaults to :yellow but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

Returns:

  • (Symbol)
336
# File 'lib/rspec/core/configuration.rb', line 336
add_setting :pending_color

#profile_examplesvoid

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Defaults profile_examples to 10 examples when @profile_examples is true.

315
# File 'lib/rspec/core/configuration.rb', line 315
add_setting :profile_examples

#project_source_dirsArray<String>

Specifies which directories contain the source code for your project. When a failure occurs, RSpec looks through the backtrace to find a a line of source to print. It first looks for a line coming from one of the project source directories so that, for example, it prints the expectation or assertion call rather than the source code from the expectation or assertion framework.

Returns:

  • (Array<String>)
309
# File 'lib/rspec/core/configuration.rb', line 309
add_setting :project_source_dirs

#requiresArray<String>

Indicates files configured to be required.

Returns:

  • (Array<String>)
251
# File 'lib/rspec/core/configuration.rb', line 251
define_reader :requires

#run_all_when_everything_filteredvoid

Deprecated.

Use #filter_run_when_matching instead for the specific filters that you want to be ignored if none match.

Run all examples if none match the configured filters (default: false).

322
# File 'lib/rspec/core/configuration.rb', line 322
add_setting :run_all_when_everything_filtered

#shared_context_metadata_behavior:trigger_inclusion, :apply_to_host_groups #shared_context_metadata_behavior=(value) ⇒ void

Configures how RSpec treats metadata passed as part of a shared example group definition. For example, given this shared example group definition:

RSpec.shared_context "uses DB", :db => true do
  around(:example) do |ex|
    MyORM.transaction(:rollback => true, &ex)
  end
end

...there are two ways RSpec can treat the :db => true metadata, each of which has a corresponding config option:

  1. :trigger_inclusion: this shared context will be implicitly included in any groups (or examples) that have :db => true metadata.
  2. :apply_to_host_groups: the metadata will be inherited by the metadata hash of all host groups and examples.

:trigger_inclusion is the legacy behavior from before RSpec 3.5 but should be considered deprecated. Instead, you can explicitly include a group with include_context:

RSpec.describe "My model" do
  include_context "uses DB"
end

...or you can configure RSpec to include the context based on matching metadata using an API that mirrors configured module inclusion:

RSpec.configure do |rspec|
  rspec.include_context "uses DB", :db => true
end

:apply_to_host_groups is a new feature of RSpec 3.5 and will be the only supported behavior in RSpec 4.

Overloads:

  • #shared_context_metadata_behavior:trigger_inclusion, :apply_to_host_groups

    Returns the configured behavior.

    Returns:

    • (:trigger_inclusion, :apply_to_host_groups)

      the configured behavior

  • #shared_context_metadata_behavior=(value) ⇒ void

    Parameters:

    • value (:trigger_inclusion, :apply_to_host_groups)

      sets the configured behavior

424
# File 'lib/rspec/core/configuration.rb', line 424
define_reader :shared_context_metadata_behavior

#silence_filter_announcementsvoid

Don't print filter info i.e. "Run options: include :focus=>true" (default false). return [Boolean]

370
# File 'lib/rspec/core/configuration.rb', line 370
add_setting :silence_filter_announcements

#success_colorSymbol

Color to use to indicate success. Defaults to :green but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

Returns:

  • (Symbol)
329
# File 'lib/rspec/core/configuration.rb', line 329
add_setting :success_color

#threadsafevoid

Use threadsafe options where available. Currently this will place a mutex around memoized values such as let blocks. return [Boolean]

445
# File 'lib/rspec/core/configuration.rb', line 445
add_setting :threadsafe

Instance Method Details

#add_formatter(formatter) ⇒ void #add_formatter(formatter, output) ⇒ void Also known as: formatter=

Adds a formatter to the set RSpec will use for this run.

Parameters:

  • formatter (Class, String, Object)

    formatter to use. Can be any of the string values supported from the CLI (p/progress, d/doc/documentation, h/html, or j/json), any class that implements the formatter protocol and has registered itself with RSpec as a formatter, or a formatter instance.

  • output (String, IO) (defaults to: output_wrapper)

    where the formatter will write its output. Can be an IO object or a string path to a file. If not provided, the configured output_stream ($stdout, by default) will be used.

See Also:

964
965
966
# File 'lib/rspec/core/configuration.rb', line 964
def add_formatter(formatter, output=output_wrapper)
  formatter_loader.add(formatter, output)
end

#add_setting(name) ⇒ void #add_setting(name, opts) ⇒ void

Adds a custom setting to the RSpec.configuration object.

RSpec.configuration.add_setting :foo

Used internally and by extension frameworks like rspec-rails, so they can add config settings that are domain specific. For example:

RSpec.configure do |c|
  c.add_setting :use_transactional_fixtures,
    :default => true,
    :alias_with => :use_transactional_examples
end

add_setting creates three methods on the configuration object, a setter, a getter, and a predicate:

RSpec.configuration.foo=(value)
RSpec.configuration.foo
RSpec.configuration.foo? # Returns true if foo returns anything but nil or false.

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :default (Symbol)

    Set a default value for the generated getter and predicate methods:

    add_setting(:foo, :default => "default value")
    
  • :alias_with (Symbol)

    Use :alias_with to alias the setter, getter, and predicate to another name, or names:

    add_setting(:foo, :alias_with => :bar)
    add_setting(:foo, :alias_with => [:bar, :baz])
    
627
628
629
630
631
632
633
# File 'lib/rspec/core/configuration.rb', line 627
def add_setting(name, opts={})
  default = opts.delete(:default)
  (class << self; self; end).class_exec do
    add_setting(name, opts)
  end
  __send__("#{name}=", default) if default
end

#after(scope = nil, *meta, &block) ⇒ void Also known as: prepend_after

Defines a after hook. See Hooks#after for full docs.

This method differs from Hooks#after in only one way: it supports the :suite scope. Hooks with the :suite scope will be run once after the last example of the entire suite is executed.

1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
# File 'lib/rspec/core/configuration.rb', line 1967
def after(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @after_suite_hooks.unshift Hooks::AfterHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.after(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

#alias_example_group_to(new_name, *args) ⇒ void

Note:

The defined aliased will also be added to the top level (e.g. main and from within modules) if expose_dsl_globally is set to true.

Creates a method that defines an example group with the provided metadata. Can be used to define example group/metadata shortcuts.

Examples:

RSpec.configure do |config|
  config.alias_example_group_to :describe_model, :type => :model
end
shared_context_for "model tests", :type => :model do
  # define common model test helper methods, `let` declarations, etc
end
# This lets you do this:

RSpec.describe_model User do
end
# ... which is the equivalent of

RSpec.describe User, :type => :model do
end

See Also:

1177
1178
1179
1180
# File 'lib/rspec/core/configuration.rb', line 1177
def alias_example_group_to(new_name, *args)
  extra_options = Metadata.build_hash_from(args)
  RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options)
end

#alias_example_to(name, *args) ⇒ void

Note:

The specific example alias below (pending) is already defined for you.

Note:

Use with caution. This extends the language used in your specs, but does not add any additional documentation. We use this in RSpec to define methods like focus and xit, but we also add docs for those methods.

Creates a method that delegates to example including the submitted args. Used internally to add variants of example like pending:

Examples:

RSpec.configure do |config|
  config.alias_example_to :pending, :pending => true
end
# This lets you do this:

RSpec.describe Thing do
  pending "does something" do
    thing = Thing.new
  end
end
# ... which is the equivalent of

RSpec.describe Thing do
  it "does something", :pending => true do
    thing = Thing.new
  end
end

Parameters:

  • name (String)

    example name alias

  • args (Array<Symbol>, Hash)

    metadata for the generated example

1145
1146
1147
1148
# File 'lib/rspec/core/configuration.rb', line 1145
def alias_example_to(name, *args)
  extra_options = Metadata.build_hash_from(args)
  RSpec::Core::ExampleGroup.define_example_method(name, extra_options)
end

#alias_it_behaves_like_to(new_name, report_label = '') ⇒ void Also known as: alias_it_should_behave_like_to

Note:

Use with caution. This extends the language used in your specs, but does not add any additional documentation. We use this in RSpec to define it_should_behave_like (for backward compatibility), but we also add docs for that method.

Define an alias for it_should_behave_like that allows different language (like "it_has_behavior" or "it_behaves_like") to be employed when including shared examples.

Examples:

RSpec.configure do |config|
  config.alias_it_behaves_like_to(:it_has_behavior, 'has behavior:')
end
# allows the user to include a shared example group like:

RSpec.describe Entity do
  it_has_behavior 'sortability' do
    let(:sortable) { Entity.new }
  end
end
# which is reported in the output as:
# Entity
#   has behavior: sortability
#     ...sortability examples here
1208
1209
1210
# File 'lib/rspec/core/configuration.rb', line 1208
def alias_it_behaves_like_to(new_name, report_label='')
  RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label)
end

#append_after(scope = nil, *meta, &block) ⇒ void

Adds block to the end of the list of after blocks in the same scope (:example, :context, or :suite), in contrast to #after, which adds the hook to the start of the list.

See Hooks#after for full after hook docs.

This method differs from Hooks#append_after in only one way: it supports the :suite scope. Hooks with the :suite scope will be run once after the last example of the entire suite is executed.

1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
# File 'lib/rspec/core/configuration.rb', line 1996
def append_after(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @after_suite_hooks << Hooks::AfterHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.append_after(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

#around(scope = nil, *meta, &block) ⇒ void

Registers block as an around hook.

See Hooks#around for full around hook docs.

2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
# File 'lib/rspec/core/configuration.rb', line 2014
def around(scope=nil, *meta, &block)
  # defeat Ruby 2.5 lazy proc allocation to ensure
  # the methods below are passed the same proc instances
  # so `Hook` equality is preserved. For more info, see:
  # https://bugs.ruby-lang.org/issues/14045#note-5
  block.__id__
  add_hook_to_existing_matching_groups(meta, scope) { |g| g.around(scope, *meta, &block) }
  super(scope, *meta, &block)
end

#backtrace_exclusion_patternsArray<Regexp>

Regexps used to exclude lines from backtraces.

Excludes lines from ruby (and jruby) source, installed gems, anything in any "bin" directory, and any of the RSpec libs (outside gem installs) by default.

You can modify the list via the getter, or replace it with the setter.

To override this behaviour and display a full backtrace, use --backtrace on the command line, in a .rspec file, or in the rspec_options attribute of RSpec's rake task.

Returns:

  • (Array<Regexp>)
665
666
667
# File 'lib/rspec/core/configuration.rb', line 665
def backtrace_exclusion_patterns
  @backtrace_formatter.exclusion_patterns
end

#backtrace_exclusion_patterns=(patterns) ⇒ void

Set regular expressions used to exclude lines in backtrace.

Parameters:

  • patterns (Array<Regexp>)

    set backtrace_formatter exlusion_patterns

671
672
673
# File 'lib/rspec/core/configuration.rb', line 671
def backtrace_exclusion_patterns=(patterns)
  @backtrace_formatter.exclusion_patterns = patterns
end

#backtrace_inclusion_patternsArray<Regexp>

Regexps used to include lines in backtraces.

Defaults to [Regexp.new Dir.getwd].

Lines that match an exclusion and an inclusion pattern will be included.

You can modify the list via the getter, or replace it with the setter.

Returns:

  • (Array<Regexp>)
684
685
686
# File 'lib/rspec/core/configuration.rb', line 684
def backtrace_inclusion_patterns
  @backtrace_formatter.inclusion_patterns
end

#backtrace_inclusion_patterns=(patterns) ⇒ void

Set regular expressions used to include lines in backtrace.

690
691
692
# File 'lib/rspec/core/configuration.rb', line 690
def backtrace_inclusion_patterns=(patterns)
  @backtrace_formatter.inclusion_patterns = patterns
end

#before(scope = nil, *meta, &block) ⇒ void Also known as: append_before

Defines a before hook. See Hooks#before for full docs.

This method differs from Hooks#before in only one way: it supports the :suite scope. Hooks with the :suite scope will be run once before the first example of the entire suite is executed.

1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
# File 'lib/rspec/core/configuration.rb', line 1914
def before(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @before_suite_hooks << Hooks::BeforeHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.before(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

#color_enabled?(output = output_stream) ⇒ Boolean

Check if color is enabled for a particular output.

Parameters:

  • output (IO) (defaults to: output_stream)

    an output stream to use, defaults to the current output_stream

Returns:

  • (Boolean)
911
912
913
914
915
916
917
918
# File 'lib/rspec/core/configuration.rb', line 911
def color_enabled?(output=output_stream)
  case color_mode
  when :on then true
  when :off then false
  else # automatic
    output_to_tty?(output) || (color && tty?)
  end
end

#default_formattervoid

The formatter that will be used if no formatter has been set. Defaults to 'progress'.

971
972
973
# File 'lib/rspec/core/configuration.rb', line 971
def default_formatter
  formatter_loader.default_formatter
end

#default_formatter=(value) ⇒ void

Sets a fallback formatter to use if none other has been set.

Examples:


RSpec.configure do |rspec|
  rspec.default_formatter = 'doc'
end
982
983
984
# File 'lib/rspec/core/configuration.rb', line 982
def default_formatter=(value)
  formatter_loader.default_formatter = value
end

#define_derived_metadata(*filters) {|metadata| ... } ⇒ void

Defines a callback that can assign derived metadata values.

Examples:

RSpec.configure do |config|
  # Tag all groups and examples in the spec/unit directory with
  # :type => :unit
  config.(:file_path => %r{/spec/unit/}) do ||
    [:type] = :unit
  end
end

Parameters:

  • filters (Array<Symbol>, Hash)

    metadata filters that determine which example or group metadata hashes the callback will be triggered for. If none are given, the callback will be run against the metadata hashes of all groups and examples.

Yield Parameters:

  • metadata (Hash)

    original metadata hash from an example or group. Mutate this in your block as needed.

1839
1840
1841
1842
# File 'lib/rspec/core/configuration.rb', line 1839
def (*filters, &block)
  meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  @derived_metadata_blocks.append(block, meta)
end

#deprecation_streamIO, String

Determines where deprecation warnings are printed. Defaults to $stderr.

Returns:

  • (IO, String)

    IO or filename to write to

162
# File 'lib/rspec/core/configuration.rb', line 162
define_reader :deprecation_stream

#deprecation_stream=(value) ⇒ void

Determines where deprecation warnings are printed.

Parameters:

  • value (IO, String)

    IO to write to or filename to write to

166
167
168
169
170
171
172
173
174
175
176
# File 'lib/rspec/core/configuration.rb', line 166
def deprecation_stream=(value)
  if @reporter && !value.equal?(@deprecation_stream)
    warn "RSpec's reporter has already been initialized with " \
      "#{deprecation_stream.inspect} as the deprecation stream, so your change to "\
      "`deprecation_stream` will be ignored. You should configure it earlier for " \
      "it to take effect, or use the `--deprecation-out` CLI option. " \
      "(Called from #{CallerFilter.first_non_rspec_line})"
  else
    @deprecation_stream = value
  end
end

#disable_monkey_patching!void

Note:

It configures rspec-mocks and rspec-expectations only if the user is using those (either explicitly or implicitly by not setting mock_with or expect_with to anything else).

Note:

If the user uses this options with mock_with :mocha (or similiar) they will still have monkey patching active in their test environment from mocha.

Enables zero monkey patching mode for RSpec. It removes monkey patching of the top-level DSL methods (describe, shared_examples_for, etc) onto main and Module, instead requiring you to prefix these methods with RSpec.. It enables expect-only syntax for rspec-mocks and rspec-expectations. It simply disables monkey patching on whatever pieces of RSpec the user is using.

Examples:


# It disables all monkey patching.
RSpec.configure do |config|
  config.disable_monkey_patching!
end
# Is an equivalent to
RSpec.configure do |config|
  config.expose_dsl_globally = false
  config.mock_with :rspec do |mocks|
    mocks.syntax = :expect
    mocks.patch_marshal_to_support_partial_doubles = false
  end
  config.expect_with :rspec do |expectations|
    expectations.syntax = :expect
  end
end
1812
1813
1814
1815
1816
1817
# File 'lib/rspec/core/configuration.rb', line 1812
def disable_monkey_patching!
  self.expose_dsl_globally = false
  self.disable_monkey_patching = true
  conditionally_disable_mocks_monkey_patching
  conditionally_disable_expectations_monkey_patching
end

#exclusion_filtervoid

Returns the exclusion_filter. If none has been set, returns an empty hash.

1337
1338
1339
# File 'lib/rspec/core/configuration.rb', line 1337
def exclusion_filter
  filter_manager.exclusions
end

#exclusion_filter=(filter) ⇒ void

Clears and reassigns the exclusion_filter. Set to nil if you don't want any exclusion filter at all.

Warning

This overrides any exclusion filters/tags set on the command line or in configuration files.

1330
1331
1332
1333
# File 'lib/rspec/core/configuration.rb', line 1330
def exclusion_filter=(filter)
  meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
  filter_manager.exclude_only meta
end

#expect_with(*frameworks) ⇒ void

Sets the expectation framework module(s) to be included in each example group.

frameworks can be :rspec, :test_unit, :minitest, a custom module, or any combination thereof:

config.expect_with :rspec
config.expect_with :test_unit
config.expect_with :minitest
config.expect_with :rspec, :minitest
config.expect_with OtherExpectationFramework

RSpec will translate :rspec, :minitest, and :test_unit into the appropriate modules.

Configuration

If the module responds to configuration, expect_with will yield the configuration object if given a block:

config.expect_with OtherExpectationFramework do |custom_config|
  custom_config.custom_setting = true
end
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
# File 'lib/rspec/core/configuration.rb', line 826
def expect_with(*frameworks)
  modules = frameworks.map do |framework|
    case framework
    when Module
      framework
    when :rspec
      require 'rspec/expectations'
      # Tag this exception class so our exception formatting logic knows
      # that it satisfies the `MultipleExceptionError` interface.
      ::RSpec::Expectations::MultipleExpectationsNotMetError.__send__(
        :include, MultipleExceptionError::InterfaceTag
      )
      ::RSpec::Matchers
    when :test_unit
      require 'rspec/core/test_unit_assertions_adapter'
      ::RSpec::Core::TestUnitAssertionsAdapter
    when :minitest
      require 'rspec/core/minitest_assertions_adapter'
      ::RSpec::Core::MinitestAssertionsAdapter
    else
      raise ArgumentError, "#{framework.inspect} is not supported"
    end
  end
  if (modules - @expectation_frameworks).any?
    assert_no_example_groups_defined(:expect_with)
  end
  if block_given?
    raise "expect_with only accepts a block with a single argument. " \
          "Call expect_with #{modules.length} times, " \
          "once with each argument, instead." if modules.length > 1
    raise "#{modules.first} must respond to `configuration` so that " \
          "expect_with can yield it." unless modules.first.respond_to?(:configuration)
    yield modules.first.configuration
  end
  @expectation_frameworks.push(*modules)
end

#expectation_framework=(framework) ⇒ void

Delegates to expect_with(framework).

799
800
801
# File 'lib/rspec/core/configuration.rb', line 799
def expectation_framework=(framework)
  expect_with(framework)
end

#expectation_frameworksvoid

Returns the configured expectation framework adapter module(s)

787
788
789
790
791
792
793
794
795
796
# File 'lib/rspec/core/configuration.rb', line 787
def expectation_frameworks
  if @expectation_frameworks.empty?
    begin
      expect_with :rspec
    rescue LoadError
      expect_with Module.new
    end
  end
  @expectation_frameworks
end

#expose_current_running_example_as(method_name) ⇒ void

Exposes the current running example via the named helper method. RSpec 2.x exposed this via example, but in RSpec 3.0, the example is instead exposed via an arg yielded to it, before, let, etc. However, some extension gems (such as Capybara) depend on the RSpec 2.x's example method, so this config option can be used to maintain compatibility.

Examples:


RSpec.configure do |rspec|
  rspec.expose_current_running_example_as :example
end
RSpec.describe MyClass do
  before do
    # `example` can be used here because of the above config.
    do_something if example.[:type] == "foo"
  end
end

Parameters:

  • method_name (Symbol)

    the name of the helper method

1750
1751
1752
1753
1754
1755
1756
1757
# File 'lib/rspec/core/configuration.rb', line 1750
def expose_current_running_example_as(method_name)
  ExposeCurrentExample.module_exec do
    extend RSpec::SharedContext
    let(method_name) { |ex| ex }
  end
  include ExposeCurrentExample
end

#expose_dsl_globally=(value) ⇒ void

Use this to expose the core RSpec DSL via Module and the main object. It will be set automatically but you can override it to remove the DSL. Default: true

149
150
151
152
153
154
155
156
157
# File 'lib/rspec/core/configuration.rb', line 149
def expose_dsl_globally=(value)
  if value
    Core::DSL.expose_globally!
    Core::SharedExampleGroup::TopLevelDSL.expose_globally!
  else
    Core::DSL.remove_globally!
    Core::SharedExampleGroup::TopLevelDSL.remove_globally!
  end
end

#expose_dsl_globally?Boolean

Indicates if the DSL has been exposed off of modules and main. Default: true

Returns:

  • (Boolean)
141
142
143
# File 'lib/rspec/core/configuration.rb', line 141
def expose_dsl_globally?
  Core::DSL.exposed_globally?
end

#extend(mod, *filters) ⇒ void

Tells RSpec to extend example groups with mod. Methods defined in mod are exposed to example groups (not examples). Use filters to constrain the groups to extend.

Similar to include, but behavior is added to example groups, which are classes, rather than the examples, which are instances of those classes.

Examples:


module UiHelpers
  def run_in_browser
    # ...
  end
end
RSpec.configure do |config|
  config.extend(UiHelpers, :type => :request)
end
describe "edit profile", :type => :request do
  run_in_browser
  it "does stuff in the client" do
    # ...
  end
end

See Also:

1460
1461
1462
1463
1464
# File 'lib/rspec/core/configuration.rb', line 1460
def extend(mod, *filters)
  define_mixed_in_module(mod, filters, @extend_modules, :extend) do |group|
    safe_extend(mod, group)
  end
end

#filter_gems_from_backtrace(*gem_names) ⇒ void

Note:

The patterns this adds will match the named gems in their common locations (e.g. system gems, vendored with bundler, installed as a :git dependency with bundler, etc) but is not guaranteed to work for all possible gem locations. For example, if you have the gem source in a directory with a completely unrelated name, and use bundler's :path option, this will not filter it.

Adds #backtrace_exclusion_patterns that will filter lines from the named gems from backtraces.

Examples:

RSpec.configure do |config|
  config.filter_gems_from_backtrace "rack", "rake"
end

Parameters:

  • gem_names (Array<String>)

    Names of the gems to filter

710
711
712
713
714
# File 'lib/rspec/core/configuration.rb', line 710
def filter_gems_from_backtrace(*gem_names)
  gem_names.each do |name|
    @backtrace_formatter.filter_gem(name)
  end
end

#filter_run_excluding(*args) ⇒ void

Adds key/value pairs to the exclusion_filter. If args includes any symbols that are not part of the hash, each symbol is treated as a key in the hash with the value true.

Note

Filters set using this method can be overridden from the command line or config files (e.g. .rspec).

Examples:

# Given this declaration.
describe "something", :foo => 'bar' do
  # ...
end
# Any of the following will exclude that group.
config.filter_run_excluding :foo => 'bar'
config.filter_run_excluding :foo => /^ba/
config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
# Given a proc with an arity of 1, the lambda is passed the value
# related to the key, e.g.
config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
# Given a proc with an arity of 2, the lambda is passed the value
# related to the key, and the metadata itself e.g.
config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
filter_run_excluding :foo # same as filter_run_excluding :foo => true
1317
1318
1319
1320
1321
# File 'lib/rspec/core/configuration.rb', line 1317
def filter_run_excluding(*args)
  meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
  filter_manager.exclude_with_low_priority meta
  static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta)
end

#filter_run_including(*args) ⇒ void Also known as: filter_run

Adds key/value pairs to the inclusion_filter. If args includes any symbols that are not part of the hash, each symbol is treated as a key in the hash with the value true.

Note

Filters set using this method can be overridden from the command line or config files (e.g. .rspec).

Examples:

# Given this declaration.
describe "something", :foo => 'bar' do
  # ...
end
# Any of the following will include that group.
config.filter_run_including :foo => 'bar'
config.filter_run_including :foo => /^ba/
config.filter_run_including :foo => lambda {|v| v == 'bar'}
config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
# Given a proc with an arity of 1, the lambda is passed the value
# related to the key, e.g.
config.filter_run_including :foo => lambda {|v| v == 'bar'}
# Given a proc with an arity of 2, the lambda is passed the value
# related to the key, and the metadata itself e.g.
config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
filter_run_including :foo # same as filter_run_including :foo => true
1243
1244
1245
1246
1247
# File 'lib/rspec/core/configuration.rb', line 1243
def filter_run_including(*args)
  meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
  filter_manager.include_with_low_priority meta
  static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta)
end

#filter_run_when_matching(*args) ⇒ void

Applies the provided filter only if any of examples match, in constrast to #filter_run, which always applies even if no examples match, in which case no examples will be run. This allows you to leave configured filters in place that are intended only for temporary use. The most common example is focus filtering: config.filter_run_when_matching :focus. With that configured, you can temporarily focus an example or group by tagging it with :focus metadata, or prefixing it with an f (as in fdescribe, fcontext and fit) since those are aliases for describe/context/it with :focus metadata.

1259
1260
1261
1262
1263
# File 'lib/rspec/core/configuration.rb', line 1259
def filter_run_when_matching(*args)
  when_first_matching_example_defined(*args) do
    filter_run(*args)
  end
end

#format_docstrings(&block) ⇒ void

Formats the docstring output using the block provided.

Examples:

# This will strip the descriptions of both examples and example
# groups.
RSpec.configure do |config|
  config.format_docstrings { |s| s.strip }
end
1601
1602
1603
# File 'lib/rspec/core/configuration.rb', line 1601
def format_docstrings(&block)
  @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER
end

#formattersArray

Returns a duplicate of the formatters currently loaded in the FormatterLoader for introspection.

Note as this is a duplicate, any mutations will be disregarded.

Returns:

  • (Array)

    the formatters currently loaded

992
993
994
# File 'lib/rspec/core/configuration.rb', line 992
def formatters
  formatter_loader.formatters.dup
end

#full_backtrace=(true_or_false) ⇒ void

Toggle full backtrace.

876
877
878
# File 'lib/rspec/core/configuration.rb', line 876
def full_backtrace=(true_or_false)
  @backtrace_formatter.full_backtrace = true_or_false
end

#full_backtrace?Boolean

Check if full backtrace is enabled.

Returns:

  • (Boolean)

    is full backtrace enabled

870
871
872
# File 'lib/rspec/core/configuration.rb', line 870
def full_backtrace?
  @backtrace_formatter.full_backtrace?
end

#full_descriptionArray

Returns full description filter.

Returns:

  • (Array)

    full description filter

945
946
947
# File 'lib/rspec/core/configuration.rb', line 945
def full_description
  filter.fetch :full_description, nil
end

#full_description=(description) ⇒ void

Run examples matching on description in all files to run.

Parameters:

  • description (String, Regexp)

    the pattern to filter on

940
941
942
# File 'lib/rspec/core/configuration.rb', line 940
def full_description=(description)
  filter_run :full_description => Regexp.union(*Array(description).map { |d| Regexp.new(d) })
end

#include(mod, *filters) ⇒ void

Note:

Filtered module inclusions can also be applied to individual examples that have matching metadata. Just like Ruby's object model is that every object has a singleton class which has only a single instance, RSpec's model is that every example has a singleton example group containing just the one example.

Tells RSpec to include mod in example groups. Methods defined in mod are exposed to examples (not example groups). Use filters to constrain the groups or examples in which to include the module.

Examples:


module AuthenticationHelpers
  def (user)
    # ...
  end
end
module UserHelpers
  def users(username)
    # ...
  end
end
RSpec.configure do |config|
  config.include(UserHelpers) # included in all groups
  config.include(AuthenticationHelpers, :type => :request)
end
describe "edit profile", :type => :request do
  it "can be viewed by owning user" do
     users(:jdoe)
    get "/profiles/jdoe"
    assert_select ".username", :text => 'jdoe'
  end
end

See Also:

1382
1383
1384
1385
1386
# File 'lib/rspec/core/configuration.rb', line 1382
def include(mod, *filters)
  define_mixed_in_module(mod, filters, @include_modules, :include) do |group|
    safe_include(mod, group)
  end
end

#include_context(shared_group_name, *filters) ⇒ void

Note:

Filtered context inclusions can also be applied to individual examples that have matching metadata. Just like Ruby's object model is that every object has a singleton class which has only a single instance, RSpec's model is that every example has a singleton example group containing just the one example.

Tells RSpec to include the named shared example group in example groups. Use filters to constrain the groups or examples in which to include the example group.

Examples:


RSpec.shared_context "example users" do
  let(:admin_user) { create_user(:admin) }
  let(:guest_user) { create_user(:guest) }
end
RSpec.configure do |config|
  config.include_context "example users", :type => :request
end
RSpec.describe "The admin page", :type => :request do
  it "can be viewed by admins" do
     admin_user
    get "/admin"
    expect(response).to be_ok
  end
  it "cannot be viewed by guests" do
     guest_user
    get "/admin"
    expect(response).to be_forbidden
  end
end

See Also:

1425
1426
1427
1428
# File 'lib/rspec/core/configuration.rb', line 1425
def include_context(shared_group_name, *filters)
  shared_module = world.shared_example_group_registry.find([:main], shared_group_name)
  include shared_module, *filters
end

#inclusion_filtervoid Also known as: filter

Returns the inclusion_filter. If none has been set, returns an empty hash.

1281
1282
1283
# File 'lib/rspec/core/configuration.rb', line 1281
def inclusion_filter
  filter_manager.inclusions
end

#inclusion_filter=(filter) ⇒ void Also known as: filter=

Clears and reassigns the inclusion_filter. Set to nil if you don't want any inclusion filter at all.

Warning

This overrides any inclusion filters/tags set on the command line or in configuration files.

1272
1273
1274
1275
# File 'lib/rspec/core/configuration.rb', line 1272
def inclusion_filter=(filter)
  meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
  filter_manager.include_only meta
end

#mock_frameworkSymbol

Returns the configured mock framework adapter module.

Returns:

  • (Symbol)
637
638
639
640
641
642
643
644
645
646
# File 'lib/rspec/core/configuration.rb', line 637
def mock_framework
  if @mock_framework.nil?
    begin
      mock_with :rspec
    rescue LoadError
      mock_with :nothing
    end
  end
  @mock_framework
end

#mock_framework=(framework) ⇒ void

Delegates to mock_framework=(framework).

649
650
651
# File 'lib/rspec/core/configuration.rb', line 649
def mock_framework=(framework)
  mock_with framework
end

#mock_with(framework) ⇒ void

Sets the mock framework adapter module.

framework can be a Symbol or a Module.

Given any of :rspec, :mocha, :flexmock, or :rr, configures the named framework.

Given :nothing, configures no framework. Use this if you don't use any mocking framework to save a little bit of overhead.

Given a Module, includes that module in every example group. The module should adhere to RSpec's mock framework adapter API:

setup_mocks_for_rspec
  - called before each example
verify_mocks_for_rspec
  - called after each example if the example hasn't yet failed.
    Framework should raise an exception when expectations fail
teardown_mocks_for_rspec
  - called after verify_mocks_for_rspec (even if there are errors)

If the module responds to configuration and mock_with receives a block, it will yield the configuration object to the block e.g.

config.mock_with OtherMockFrameworkAdapter do |mod_config|
  mod_config.custom_setting = true
end
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'lib/rspec/core/configuration.rb', line 754
def mock_with(framework)
  framework_module =
    if framework.is_a?(Module)
      framework
    else
      const_name = MOCKING_ADAPTERS.fetch(framework) do
        raise ArgumentError,
              "Unknown mocking framework: #{framework.inspect}. " \
              "Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}"
      end
      RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}"
      RSpec::Core::MockingAdapters.const_get(const_name)
    end
  new_name, old_name = [framework_module, @mock_framework].map do |mod|
    mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed
  end
  unless new_name == old_name
    assert_no_example_groups_defined(:mock_framework)
  end
  if block_given?
    raise "#{framework_module} must respond to `configuration` so that " \
          "mock_with can yield it." unless framework_module.respond_to?(:configuration)
    yield framework_module.configuration
  end
  @mock_framework = framework_module
end

#on_example_group_definition(&block) ⇒ void

Invokes block before defining an example group

2046
2047
2048
# File 'lib/rspec/core/configuration.rb', line 2046
def on_example_group_definition(&block)
  on_example_group_definition_callbacks << block
end

#on_example_group_definition_callbacksvoid

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns an array of blocks to call before defining an example group

2052
2053
2054
# File 'lib/rspec/core/configuration.rb', line 2052
def on_example_group_definition_callbacks
  @on_example_group_definition_callbacks ||= []
end

#order=(value) ⇒ void

Sets the default global ordering strategy. By default this can be one of :defined, :random, but is customizable through the register_ordering API. If order is set to 'rand:<seed>', the seed will also be set.

See Also:

1646
# File 'lib/rspec/core/configuration.rb', line 1646
delegate_to_ordering_manager :order=

#prepend(mod, *filters) ⇒ void

Tells RSpec to prepend example groups with mod. Methods defined in mod are exposed to examples (not example groups). Use filters to constrain the groups in which to prepend the module.

Similar to include, but module is included before the example group's class in the ancestor chain.

Examples:


module OverrideMod
  def override_me
    "overridden"
  end
end
RSpec.configure do |config|
  config.prepend(OverrideMod, :method => :prepend)
end
describe "overriding example's class", :method => :prepend do
  it "finds the user" do
    self.class.class_eval do
      def override_me
      end
    end
    override_me # => "overridden"
    # ...
  end
end

See Also:

1499
1500
1501
1502
1503
# File 'lib/rspec/core/configuration.rb', line 1499
def prepend(mod, *filters)
  define_mixed_in_module(mod, filters, @prepend_modules, :prepend) do |group|
    safe_prepend(mod, group)
  end
end

#prepend_before(scope = nil, *meta, &block) ⇒ void

Adds block to the start of the list of before blocks in the same scope (:example, :context, or :suite), in contrast to #before, which adds the hook to the end of the list.

See Hooks#before for full before hook docs.

This method differs from Hooks#prepend_before in only one way: it supports the :suite scope. Hooks with the :suite scope will be run once before the first example of the entire suite is executed.

1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
# File 'lib/rspec/core/configuration.rb', line 1943
def prepend_before(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @before_suite_hooks.unshift Hooks::BeforeHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.prepend_before(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

#raise_errors_for_deprecations!void

Turns deprecation warnings into errors, in order to surface the full backtrace of the call site. This can be useful when you need more context to address a deprecation than the single-line call site normally provided.

Examples:


RSpec.configure do |rspec|
  rspec.raise_errors_for_deprecations!
end
1772
1773
1774
# File 'lib/rspec/core/configuration.rb', line 1772
def raise_errors_for_deprecations!
  self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new
end

#raise_on_warning=(value) ⇒ void

Turns warnings into errors. This can be useful when you want RSpec to run in a 'strict' no warning situation.

Examples:


RSpec.configure do |rspec|
  rspec.raise_on_warning = true
end
1720
1721
1722
1723
1724
1725
1726
# File 'lib/rspec/core/configuration.rb', line 1720
def raise_on_warning=(value)
  if value
    RSpec::Support.warning_notifier = RAISE_ERROR_WARNING_NOTIFIER
  else
    RSpec::Support.warning_notifier = RSpec::Support::DEFAULT_WARNING_NOTIFIER
  end
end

#register_ordering(name) {|list| ... } ⇒ void

Note:

Pass the symbol :global to set the ordering strategy that will be used to order the top-level example groups and any example groups that do not have declared :order metadata.

Registers a named ordering strategy that can later be used to order an example group's subgroups by adding :order => <name> metadata to the example group.

Examples:

RSpec.configure do |rspec|
  rspec.register_ordering :reverse do |list|
    list.reverse
  end
end
RSpec.describe 'MyClass', :order => :reverse do
  # ...
end
RSpec.configure do |rspec|
  rspec.register_ordering :global do |examples|
    acceptance, other = examples.partition do |example|
      example.[:type] == :acceptance
    end
    other + acceptance
  end
end
RSpec.describe 'MyClass', :type => :acceptance do
  # will run last
end
RSpec.describe 'MyClass' do
  # will run first
end

Parameters:

  • name (Symbol)

    The name of the ordering.

Yields:

  • Block that will order the given examples or example groups

Yield Parameters:

Yield Returns:

1694
# File 'lib/rspec/core/configuration.rb', line 1694
delegate_to_ordering_manager :register_ordering

#reporterRSpec::Core::Reporter

Returns the currently configured reporter.

Returns:

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
# File 'lib/rspec/core/configuration.rb', line 1024
def reporter
  # @reporter_buffer should only ever be set in this method to cover
  # initialization of @reporter.
  @reporter_buffer || @reporter ||=
    begin
      @reporter_buffer = DeprecationReporterBuffer.new
      formatter_loader.prepare_default output_wrapper, deprecation_stream
      @reporter_buffer.play_onto(formatter_loader.reporter)
      @reporter_buffer = nil
      formatter_loader.reporter
    end
end

#seedvoid

Seed for random ordering (default: generated randomly each run).

When you run specs with --order random, RSpec generates a random seed for the randomization and prints it to the output_stream (assuming you're using RSpec's built-in formatters). If you discover an ordering dependency (i.e. examples fail intermittently depending on order), set this (on Configuration or on the command line with --seed) to run using the same seed while you debug the issue.

We recommend, actually, that you use the command line approach so you don't accidentally leave the seed encoded.

1636
# File 'lib/rspec/core/configuration.rb', line 1636
delegate_to_ordering_manager :seed

#seed=(value) ⇒ void

Sets the seed value and sets the default global ordering to random.

1622
# File 'lib/rspec/core/configuration.rb', line 1622
delegate_to_ordering_manager :seed=

#treat_symbols_as_metadata_keys_with_true_values=(_value) ⇒ void

Deprecated.

This config option was added in RSpec 2 to pave the way for this being the default behavior in RSpec 3. Now this option is a no-op.

375
376
377
378
379
380
381
382
# File 'lib/rspec/core/configuration.rb', line 375
def (_value)
  RSpec.deprecate(
    "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=",
    :message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " \
                "is deprecated, it is now set to true as default and " \
                "setting it to false has no effect."
  )
end

#warnings=(value) ⇒ void

Set Ruby warnings on or off.

1700
1701
1702
# File 'lib/rspec/core/configuration.rb', line 1700
def warnings=(value)
  $VERBOSE = !!value
end

#warnings?Boolean

Returns Whether or not ruby warnings are enabled.

Returns:

  • (Boolean)

    Whether or not ruby warnings are enabled.

1705
1706
1707
# File 'lib/rspec/core/configuration.rb', line 1705
def warnings?
  $VERBOSE
end

#when_first_matching_example_defined(*filters) ⇒ void

Defines a callback that runs after the first example with matching metadata is defined. If no examples are defined with matching metadata, it will not get called at all.

This can be used to ensure some setup is performed (such as bootstrapping a DB or loading a specific file that adds significantly to the boot time) if needed (as indicated by the presence of an example with matching metadata) but avoided otherwise.

Examples:

RSpec.configure do |config|
  config.when_first_matching_example_defined(:db) do
    # Load a support file that does some heavyweight setup,
    # including bootstrapping the DB, but only if we have loaded
    # any examples tagged with `:db`.
    require 'support/db'
  end
end
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
# File 'lib/rspec/core/configuration.rb', line 1862
def when_first_matching_example_defined(*filters)
  specified_meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  callback = lambda do |example_or_group_meta|
    # Example groups do not have `:example_group` metadata
    # (instead they have `:parent_example_group` metadata).
    return unless example_or_group_meta.key?(:example_group)
    # Ensure the callback only fires once.
    @derived_metadata_blocks.delete(callback, specified_meta)
    yield
  end
  @derived_metadata_blocks.append(callback, specified_meta)
end