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 ~/.rspec, .rspec, .rspec-local, command line switches, and the SPEC_OPTS environment variable (listed in lowest to highest precedence; for example, an option in ~/.rspec can be overridden by an option in .rspec-local).

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:

Constant Summary

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Methods included from Hooks

#around

Constructor Details

- (Configuration) initialize

Returns a new instance of Configuration

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/rspec/core/configuration.rb', line 327
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?)
  @before_suite_hooks = []
  @after_suite_hooks  = []
  @mock_framework = nil
  @files_or_directories_to_run = []
  @loaded_spec_files = Set.new
  @color = false
  @pattern = '**{,/*/**}/*_spec.rb'
  @exclude_pattern = ''
  @failure_exit_code = 1
  @spec_files_loaded = false
  @backtrace_formatter = BacktraceFormatter.new
  @default_path = 'spec'
  @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
  define_built_in_hooks
end

Instance Attribute Details

- (void) default_color

The default output color.

Parameters:

  • color (Symbol)

    defaults to :white but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

280
# File 'lib/rspec/core/configuration.rb', line 280
add_setting :default_color

- (void) default_path

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.

103
# File 'lib/rspec/core/configuration.rb', line 103
add_setting :default_path

- (void) detail_color

Color used to print details.

Parameters:

  • color (Symbol)

    defaults to :cyan but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

294
# File 'lib/rspec/core/configuration.rb', line 294
add_setting :detail_color

- (void) drb

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

108
# File 'lib/rspec/core/configuration.rb', line 108
add_setting :drb

- (void) drb_port

The drb_port (default: nil).

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

- (void) dry_run

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

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

- (void) error_stream

Default: $stderr.

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

- (String) example_status_persistence_file_path - (void) example_status_persistence_file_path=(value)

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

Overloads:

  • - (String) example_status_persistence_file_path

    Returns the file path

    Returns:

    • (String)

      the file path

  • - (void) example_status_persistence_file_path=(value)

    Parameters:

    • value (String)

      the file path

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

- (void) exclude_pattern

Exclude files matching this pattern.

236
# File 'lib/rspec/core/configuration.rb', line 236
define_reader :exclude_pattern

- (void) fail_fast

Clean up and exit after the first failure (default: false).

186
# File 'lib/rspec/core/configuration.rb', line 186
add_setting :fail_fast

- (void) failure_color

Color to use to indicate failure.

Parameters:

  • color (Symbol)

    defaults to :red but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

273
# File 'lib/rspec/core/configuration.rb', line 273
add_setting :failure_color

- (void) failure_exit_code

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

195
# File 'lib/rspec/core/configuration.rb', line 195
add_setting :failure_exit_code

- (Array) files_to_run

The spec files RSpec will run.

Returns:

  • (Array)

    specified files about to run

851
852
853
# File 'lib/rspec/core/configuration.rb', line 851
def files_to_run
  @files_to_run ||= get_files_to_run(@files_or_directories_to_run)
end

- (void) fixed_color

Color used when a pending example is fixed.

Parameters:

  • color (Symbol)

    defaults to :blue but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

287
# File 'lib/rspec/core/configuration.rb', line 287
add_setting :fixed_color

- (void) libs

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

204
# File 'lib/rspec/core/configuration.rb', line 204
define_reader :libs

- (void) only_failures (readonly) Also known as: only_failures?

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

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

- (void) output_stream

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

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

- (void) pattern

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

226
# File 'lib/rspec/core/configuration.rb', line 226
define_reader :pattern

- (void) pending_color

Color to use to print pending examples.

Parameters:

  • color (Symbol)

    defaults to :yellow but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

266
# File 'lib/rspec/core/configuration.rb', line 266
add_setting :pending_color

- (void) profile_examples

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.

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

- (void) requires

Indicates files configured to be required.

199
# File 'lib/rspec/core/configuration.rb', line 199
define_reader :requires

- (void) run_all_when_everything_filtered

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

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

- (void) success_color

Color to use to indicate success.

Parameters:

  • color (Symbol)

    defaults to :green but can be set to one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

259
# File 'lib/rspec/core/configuration.rb', line 259
add_setting :success_color

- (void) threadsafe

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

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

Instance Method Details

- (void) add_formatter(formatter) Also known as: formatter=

Adds a formatter to the formatters collection. formatter can be a string representing any of the built-in formatters (see built_in_formatter), or a custom formatter class.

Note

For internal purposes, add_formatter also accepts the name of a class and paths to use for output streams, but you should consider that a private api that may change at any time without notice.

750
751
752
753
# File 'lib/rspec/core/configuration.rb', line 750
def add_formatter(formatter_to_use, *paths)
  paths << output_stream if paths.empty?
  formatter_loader.add formatter_to_use, *paths
end

- (void) add_setting(name) - (void) add_setting(name, opts)

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])
    
438
439
440
441
442
443
444
# File 'lib/rspec/core/configuration.rb', line 438
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

- (void) after(*args, &block) 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.

1596
1597
1598
1599
# File 'lib/rspec/core/configuration.rb', line 1596
def after(*args, &block)
  handle_suite_hook(args, @after_suite_hooks, :unshift,
                    Hooks::AfterHook, block) || super(*args, &block)
end

- (void) alias_example_group_to(new_name, *args)

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:

953
954
955
956
# File 'lib/rspec/core/configuration.rb', line 953
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

- (void) alias_example_to(name, *args)

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:

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

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

921
922
923
924
# File 'lib/rspec/core/configuration.rb', line 921
def alias_example_to(name, *args)
  extra_options = Metadata.build_hash_from(args)
  RSpec::Core::ExampleGroup.define_example_method(name, extra_options)
end

- (void) alias_it_behaves_like_to(new_name, report_label = '') 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:

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
984
985
986
# File 'lib/rspec/core/configuration.rb', line 984
def alias_it_behaves_like_to(new_name, report_label='')
  RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label)
end

- (void) append_after(*args, &block)

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.

1615
1616
1617
1618
# File 'lib/rspec/core/configuration.rb', line 1615
def append_after(*args, &block)
  handle_suite_hook(args, @after_suite_hooks, :push,
                    Hooks::AfterHook, block) || super(*args, &block)
end

- (void) backtrace_exclusion_patterns

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.

474
475
476
# File 'lib/rspec/core/configuration.rb', line 474
def backtrace_exclusion_patterns
  @backtrace_formatter.exclusion_patterns
end

- (void) backtrace_exclusion_patterns=(patterns)

Set regular expressions used to exclude lines in backtrace.

Parameters:

  • patterns (Regexp)

    set the backtrace exlusion pattern

480
481
482
# File 'lib/rspec/core/configuration.rb', line 480
def backtrace_exclusion_patterns=(patterns)
  @backtrace_formatter.exclusion_patterns = patterns
end

- (void) backtrace_inclusion_patterns

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.

492
493
494
# File 'lib/rspec/core/configuration.rb', line 492
def backtrace_inclusion_patterns
  @backtrace_formatter.inclusion_patterns
end

- (void) backtrace_inclusion_patterns=(patterns)

Set regular expressions used to include lines in backtrace.

498
499
500
# File 'lib/rspec/core/configuration.rb', line 498
def backtrace_inclusion_patterns=(patterns)
  @backtrace_formatter.inclusion_patterns = patterns
end

- (void) before(*args, &block) 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.

1563
1564
1565
1566
# File 'lib/rspec/core/configuration.rb', line 1563
def before(*args, &block)
  handle_suite_hook(args, @before_suite_hooks, :push,
                    Hooks::BeforeHook, block) || super(*args, &block)
end

- (Boolean) color

Returns the configuration option for color, but should not be used to check if color is supported.

Returns:

  • (Boolean)

See Also:

  • color_enabled?
693
694
695
# File 'lib/rspec/core/configuration.rb', line 693
def color
  value_for(:color) { @color }
end

- (void) color=(true_or_false)

Toggle output color.

707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/rspec/core/configuration.rb', line 707
def color=(true_or_false)
  return unless true_or_false
  if RSpec::Support::OS.windows? && !ENV['ANSICON']
    RSpec.warning "You must use ANSICON 1.31 or later " \
                  "(http://adoxa.3eeweb.com/ansicon/) to use colour " \
                  "on Windows"
    @color = false
  else
    @color = true
  end
end

- (Boolean) color_enabled?(output = output_stream)

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)
701
702
703
# File 'lib/rspec/core/configuration.rb', line 701
def color_enabled?(output=output_stream)
  output_to_tty?(output) && color
end

- (void) default_formatter

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

758
759
760
# File 'lib/rspec/core/configuration.rb', line 758
def default_formatter
  formatter_loader.default_formatter
end

- (void) default_formatter=(value)

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

Examples:


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

- (void) define_derived_metadata(*filters) {|metadata| ... }

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.

1542
1543
1544
1545
# File 'lib/rspec/core/configuration.rb', line 1542
def (*filters, &block)
  meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  @derived_metadata_blocks.append(block, meta)
end

- (IO, String) deprecation_stream

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

Returns:

  • (IO, String)

    IO to write to or filename to write to

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

- (void) deprecation_stream=(value)

Determines where deprecation warnings are printed.

Parameters:

  • value (IO, String)

    IO to write to or filename to write to

145
146
147
148
149
150
151
152
153
154
155
# File 'lib/rspec/core/configuration.rb', line 145
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

- (void) disable_monkey_patching!

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.mock_with :rspec do |expectations|
    expectations.syntax = :expect
  end
end
1515
1516
1517
1518
1519
1520
# File 'lib/rspec/core/configuration.rb', line 1515
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

- (void) exclusion_filter

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

1099
1100
1101
# File 'lib/rspec/core/configuration.rb', line 1099
def exclusion_filter
  filter_manager.exclusions
end

- (void) exclusion_filter=(filter)

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.

1092
1093
1094
1095
# File 'lib/rspec/core/configuration.rb', line 1092
def exclusion_filter=(filter)
  meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
  filter_manager.exclude_only meta
end

- (void) expect_with(*frameworks)

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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'lib/rspec/core/configuration.rb', line 634
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

- (void) expectation_framework=(framework)

Delegates to expect_with(framework).

607
608
609
# File 'lib/rspec/core/configuration.rb', line 607
def expectation_framework=(framework)
  expect_with(framework)
end

- (void) expectation_frameworks

Returns the configured expectation framework adapter module(s)

595
596
597
598
599
600
601
602
603
604
# File 'lib/rspec/core/configuration.rb', line 595
def expectation_frameworks
  if @expectation_frameworks.empty?
    begin
      expect_with :rspec
    rescue LoadError
      expect_with Module.new
    end
  end
  @expectation_frameworks
end

- (void) expose_current_running_example_as(method_name)

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
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

1453
1454
1455
1456
1457
1458
1459
1460
# File 'lib/rspec/core/configuration.rb', line 1453
def expose_current_running_example_as(method_name)
  ExposeCurrentExample.module_exec do
    extend RSpec::SharedContext
    let(method_name) { |ex| ex }
  end
  include ExposeCurrentExample
end

- (void) expose_dsl_globally=(value)

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

128
129
130
131
132
133
134
135
136
# File 'lib/rspec/core/configuration.rb', line 128
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

- (Boolean) expose_dsl_globally?

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

Returns:

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

- (void) extend(mod, *filters)

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:

1179
1180
1181
1182
1183
# File 'lib/rspec/core/configuration.rb', line 1179
def extend(mod, *filters)
  meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  @extend_modules.append(mod, meta)
  configure_existing_groups(mod, meta, :safe_extend)
end

- (void) filter_gems_from_backtrace(*gem_names)

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

518
519
520
521
522
# File 'lib/rspec/core/configuration.rb', line 518
def filter_gems_from_backtrace(*gem_names)
  gem_names.each do |name|
    @backtrace_formatter.filter_gem(name)
  end
end

- (void) filter_run_excluding(*args)

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
1079
1080
1081
1082
1083
# File 'lib/rspec/core/configuration.rb', line 1079
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

- (void) filter_run_including(*args) 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
1019
1020
1021
1022
1023
# File 'lib/rspec/core/configuration.rb', line 1019
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

- (void) format_docstrings(&block)

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
1345
1346
1347
# File 'lib/rspec/core/configuration.rb', line 1345
def format_docstrings(&block)
  @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER
end

- (Array) formatters

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

779
780
781
# File 'lib/rspec/core/configuration.rb', line 779
def formatters
  formatter_loader.formatters.dup
end

- (void) full_backtrace=(true_or_false)

Toggle full backtrace.

684
685
686
# File 'lib/rspec/core/configuration.rb', line 684
def full_backtrace=(true_or_false)
  @backtrace_formatter.full_backtrace = true_or_false
end

- (Boolean) full_backtrace?

Check if full backtrace is enabled.

Returns:

  • (Boolean)

    is full backtrace enabled

678
679
680
# File 'lib/rspec/core/configuration.rb', line 678
def full_backtrace?
  @backtrace_formatter.full_backtrace?
end

- (Array) full_description

Returns full description filter

Returns:

  • (Array)

    full description filter

735
736
737
# File 'lib/rspec/core/configuration.rb', line 735
def full_description
  filter.fetch :full_description, nil
end

- (void) full_description=(description)

Run examples matching on description in all files to run.

Parameters:

  • description (String, Regexp)

    the pattern to filter on

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

- (void) include(mod, *filters)

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 modules
  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:

1143
1144
1145
1146
1147
# File 'lib/rspec/core/configuration.rb', line 1143
def include(mod, *filters)
  meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  @include_modules.append(mod, meta)
  configure_existing_groups(mod, meta, :safe_include)
end

- (void) inclusion_filter Also known as: filter

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

1043
1044
1045
# File 'lib/rspec/core/configuration.rb', line 1043
def inclusion_filter
  filter_manager.inclusions
end

- (void) inclusion_filter=(filter) 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.

1034
1035
1036
1037
# File 'lib/rspec/core/configuration.rb', line 1034
def inclusion_filter=(filter)
  meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
  filter_manager.include_only meta
end

- (void) mock_framework

Returns the configured mock framework adapter module.

447
448
449
450
451
452
453
454
455
456
# File 'lib/rspec/core/configuration.rb', line 447
def mock_framework
  if @mock_framework.nil?
    begin
      mock_with :rspec
    rescue LoadError
      mock_with :nothing
    end
  end
  @mock_framework
end

- (void) mock_framework=(framework)

Delegates to mock_framework=(framework).

459
460
461
# File 'lib/rspec/core/configuration.rb', line 459
def mock_framework=(framework)
  mock_with framework
end

- (void) mock_with(framework)

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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/rspec/core/configuration.rb', line 562
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

- (void) order=

Sets the default global order and, if order is 'rand:<seed>', also sets the seed.

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

- (void) prepend(mod, *filters)

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:

1218
1219
1220
1221
1222
# File 'lib/rspec/core/configuration.rb', line 1218
def prepend(mod, *filters)
  meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  @prepend_modules.append(mod, meta)
  configure_existing_groups(mod, meta, :safe_prepend)
end

- (void) prepend_before(*args, &block)

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.

1582
1583
1584
1585
# File 'lib/rspec/core/configuration.rb', line 1582
def prepend_before(*args, &block)
  handle_suite_hook(args, @before_suite_hooks, :unshift,
                    Hooks::BeforeHook, block) || super(*args, &block)
end

- (void) raise_errors_for_deprecations!

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
1475
1476
1477
# File 'lib/rspec/core/configuration.rb', line 1475
def raise_errors_for_deprecations!
  self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new
end

- (void) register_ordering {|list| ... }

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
describe MyClass, :order => :reverse do
  # ...
end

Parameters:

  • name (Symbol)

    The name of the ordering.

Yields:

  • Block that will order the given examples or example groups

Yield Parameters:

Yield Returns:

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

- (void) seed

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

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

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

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

- (void) seed=

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

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

- (void) treat_symbols_as_metadata_keys_with_true_values=(_value)

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.

299
300
301
302
303
304
305
306
# File 'lib/rspec/core/configuration.rb', line 299
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

- (void) warnings=(value)

Set Ruby warnings on or off.

1422
1423
1424
# File 'lib/rspec/core/configuration.rb', line 1422
def warnings=(value)
  $VERBOSE = !!value
end

- (Boolean) warnings?

Returns Whether or not ruby warnings are enabled.

Returns:

  • (Boolean)

    Whether or not ruby warnings are enabled.

1427
1428
1429
# File 'lib/rspec/core/configuration.rb', line 1427
def warnings?
  $VERBOSE
end