class RSpec::Core::Configuration
Stores runtime configuration information.
Configuration options are loaded from multiple files and joined together with command-line switches and the ‘SPEC_OPTS` environment variable.
Precedence order (where later entries overwrite earlier entries on conflicts):
* Global (`$XDG_CONFIG_HOME/rspec/options`, or `~/.rspec` if it does not exist) * Project-specific (`./.rspec`) * Local (`./.rspec-local`) * Command-line options * `SPEC_OPTS`
For example, an option set in the local file will override an option set in your global file.
The global, project-specific and local files can all be overridden with a separate custom file using the –options command-line parameter.
@example Standard settings
RSpec.configure do |c| c.drb = true c.drb_port = 1234 c.default_path = 'behavior' end
@example Hooks
RSpec.configure do |c| c.before(:suite) { establish_connection } c.before(:example) { log_in_as :authorized } c.around(:example) { |ex| Database.transaction(&ex) } end
@see RSpec.configure @see Hooks
Constants
- DEFAULT_FORMATTER
-
@private
- FAILED_STATUS
-
@private
- MOCKING_ADAPTERS
-
@private
- PASSED_STATUS
-
@private
- PENDING_STATUS
-
@private
- RAISE_ERROR_WARNING_NOTIFIER
-
@private
- Readers
-
Module that holds ‘attr_reader` declarations. It’s in a separate module to allow us to override those methods and use ‘super`. @private
- UNKNOWN_STATUS
-
@private
- VALID_STATUSES
-
@private
Attributes
@private
Determines which bisect runner implementation gets used to run subsets of the suite during a bisection. Your choices are:
- `:shell`: Performs a spec run by shelling out, booting RSpec and your application environment each time. This runner is the most widely compatible runner, but is not as fast. On platforms that do not support forking, this is the default. - `:fork`: Pre-boots RSpec and your application environment in a parent process, and then forks a child process for each spec run. This runner tends to be significantly faster than the `:shell` runner but cannot be used in some situations. On platforms that support forking, this is the default. If you use this runner, you should ensure that all of your one-time setup logic goes in a `before(:suite)` hook instead of getting run at the top-level of a file loaded by `--require`.
@note This option will only be used by ‘–bisect` if you set it in a file
loaded via `--require`.
@return [Symbol]
Set the color mode.
@private
@private
@private
@private
@macro add_setting Report the times for the slowest examples (default: ‘false`). Use this to specify the number of examples to include in the profile. @return [Boolean]
@private
@return [Symbol] The configured warning level
@private
Public Class Methods
@private
As ‘add_setting` but only add the reader.
# File rspec-core/lib/rspec/core/configuration.rb, line 101 def self.add_read_only_setting(name, opts={}) raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default) define_reader name define_predicate name end
@private
Invoked by the ‘add_setting` instance method. Use that method on a `Configuration` instance rather than this class method.
# File rspec-core/lib/rspec/core/configuration.rb, line 88 def self.add_setting(name, opts={}) raise "Use the instance add_setting method if you want to set a default" if opts.key?(:default) attr_writer name add_read_only_setting name Array(opts[:alias_with]).each do |alias_name| define_alias(name, alias_name) end end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 71 def self.define_alias(name, alias_name) alias_method alias_name, name alias_method "#{alias_name}=", "#{name}=" define_predicate alias_name end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 78 def self.define_predicate(name) define_method "#{name}?" do !!send(name) end end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 61 def self.define_reader(name) Readers.class_eval do remove_method name if method_defined?(name) attr_reader name end define_method(name) { value_for(name) { super() } } end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1557 def self.delegate_to_ordering_manager(*methods) methods.each do |method| define_method method do |*args, &block| ordering_manager.__send__(method, *args, &block) end end end
Build an object to store runtime configuration options and set defaults
# File rspec-core/lib/rspec/core/configuration.rb, line 438 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 @extend_modules = FilterableItemRepository::QueryOptimized.new @prepend_modules = FilterableItemRepository::QueryOptimized.new @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_mode = :automatic @pattern = '**{,/*/**}/*_spec.rb' @exclude_pattern = '' @failure_exit_code = 1 @error_exit_code = nil # so it can be overridden by failure exit code @fail_if_no_examples = false @spec_files_loaded = false @backtrace_formatter = BacktraceFormatter.new @default_path = 'spec' @project_source_dirs = %w[ spec lib app ] @deprecation_stream = $stderr @output_stream = $stdout @reporter = nil @reporter_buffer = nil @filter_manager = FilterManager.new @static_config_filter_manager = FilterManager.new @ordering_manager = Ordering::ConfigurationManager.new @preferred_options = {} @failure_color = :red @success_color = :green @pending_color = :yellow @default_color = :white @fixed_color = :blue @detail_color = :cyan @profile_examples = false @requires = [] @libs = [] @derived_metadata_blocks = FilterableItemRepository::QueryOptimized.new @threadsafe = true @max_displayed_failure_line_count = 10 @full_cause_backtrace = false @world = World::Null @pending_failure_output = :full @force_line_number_for_spec_rerun = false @warnings = nil if warnings? # Turn on all warnings if warnings already configured self.warnings = :all else # Turn on Ruby deprecations by default self.warnings = :deprecations_only end define_built_in_hooks end
Public Instance Methods
@overload add_formatter(formatter) @overload add_formatter(formatter, output)
@param formatter [Class, String, Object] formatter to use. Can be any of the
string values supported from the CLI (`p`/`progress`, `d`/`doc`/`documentation`, `h`/`html`, or `j`/`json`), any class that implements the formatter protocol and has registered itself with RSpec as a formatter, or a formatter instance.
@param output [String, IO] where the formatter will write its output.
Can be an IO object or a string path to a file. If not provided, the configured `output_stream` (`$stdout`, by default) will be used.
Adds a formatter to the set RSpec will use for this run.
@see RSpec::Core::Formatters::Protocol
# File rspec-core/lib/rspec/core/configuration.rb, line 893 def add_formatter(formatter, output=output_wrapper) formatter_loader.add(formatter, output) end
@overload add_setting(name) @overload add_setting(name, opts) @option opts [Symbol] :default
Set a default value for the generated getter and predicate methods:
add_setting(:foo, :default => "default value")
@option opts [Symbol] :alias_with
Use `:alias_with` to alias the setter, getter, and predicate to
another name, or names:
add_setting(:foo, :alias_with => :bar)
add_setting(:foo, :alias_with => [:bar, :baz])
Adds a custom setting to the RSpec.configuration object.
RSpec.configuration.add_setting :foo
Used internally and by extension frameworks like rspec-rails, so they can add config settings that are domain specific. For example:
RSpec.configure do |c| c.add_setting :use_transactional_fixtures, :default => true, :alias_with => :use_transactional_examples end
‘add_setting` creates three methods on the configuration object, a setter, a getter, and a predicate:
RSpec.configuration.foo=(value) RSpec.configuration.foo RSpec.configuration.foo? # Returns true if foo returns anything but nil or false.
# File rspec-core/lib/rspec/core/configuration.rb, line 577 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
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. Conditions passed along with `:suite` are effectively ignored.
@see append_after @see before @see prepend_before
RSpec::Core::Hooks#after
# File rspec-core/lib/rspec/core/configuration.rb, line 1886 def after(scope=nil, *meta, &block) handle_suite_hook(scope, meta) do @after_suite_hooks.unshift Hooks::AfterHook.new(block, {}) end || begin add_hook_to_existing_matching_groups(meta, scope) { |g| g.after(scope, *meta, &block) } super(scope, *meta, &block) end end
Creates a method that defines an example group with the provided metadata. Can be used to define example group/metadata shortcuts.
@example
RSpec.configure do |config| config.alias_example_group_to :describe_model, :type => :model end shared_context_for "model tests", :type => :model do # define common model test helper methods, `let` declarations, etc end # This lets you do this: RSpec.describe_model User do end # ... which is the equivalent of RSpec.describe User, :type => :model do end
@see alias_example_to
# File rspec-core/lib/rspec/core/configuration.rb, line 1102 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
Creates a method that delegates to ‘example` including the submitted `args`. Used internally to add variants of `example` like `pending`: @param name [String] example name alias @param args [Array<Symbol>, Hash] metadata for the generated example
@note The specific example alias below (‘pending`) is already
defined for you.
@note Use with caution. This extends the language used in your
specs, but does not add any additional documentation. We use this in RSpec to define methods like `focus` and `xit`, but we also add docs for those methods.
@example
RSpec.configure do |config| config.alias_example_to :pending, :pending => true end # This lets you do this: RSpec.describe Thing do pending "does something" do thing = Thing.new end end # ... which is the equivalent of RSpec.describe Thing do it "does something", :pending => true do thing = Thing.new end end
# File rspec-core/lib/rspec/core/configuration.rb, line 1074 def alias_example_to(name, *args) extra_options = Metadata.build_hash_from(args) RSpec::Core::ExampleGroup.define_example_method(name, extra_options) end
Define an alias for it_behaves_like that allows different language (like “it_has_behavior” or “it_is_able_to”) to be employed when including shared examples.
@example
RSpec.configure do |config| config.alias_it_behaves_like_to(:it_has_behavior, 'has behavior:') end # allows the user to include a shared example group like: RSpec.describe Entity do it_has_behavior 'sortability' do let(:sortable) { Entity.new } end end # which is reported in the output as: # Entity # has behavior: sortability # ...sortability examples here
@note Use with caution. This extends the language used in your
specs, but does not add any additional documentation.
# File rspec-core/lib/rspec/core/configuration.rb, line 1131 def alias_it_behaves_like_to(new_name, report_label='') RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label) end
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. Conditions passed along with `:suite` are effectively ignored.
@see append_after @see before @see prepend_before
RSpec::Core::Hooks#append_after
# File rspec-core/lib/rspec/core/configuration.rb, line 1910 def append_after(scope=nil, *meta, &block) handle_suite_hook(scope, meta) do @after_suite_hooks << Hooks::AfterHook.new(block, {}) end || begin add_hook_to_existing_matching_groups(meta, scope) { |g| g.append_after(scope, *meta, &block) } super(scope, *meta, &block) end end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1808 def apply_derived_metadata_to(metadata) already_run_blocks = Set.new # We loop and attempt to re-apply metadata blocks to support cascades # (e.g. where a derived bit of metadata triggers the application of # another piece of derived metadata, etc) # # We limit our looping to 200 times as a way to detect infinitely recursing derived metadata blocks. # It's hard to imagine a valid use case for a derived metadata cascade greater than 200 iterations. 200.times do return if @derived_metadata_blocks.items_for(metadata).all? do |block| already_run_blocks.include?(block).tap do |skip_block| block.call(metadata) unless skip_block already_run_blocks << block end end end # If we got here, then `@derived_metadata_blocks.items_for(metadata).all?` never returned # `true` above and we treat this as an attempt to recurse infinitely. It's better to fail # with a clear # error than hang indefinitely, which is what would happen if we didn't limit # the looping above. raise SystemStackError, "Attempted to recursively derive metadata indefinitely." end
Registers ‘block` as an `around` hook.
See {Hooks#around} for full ‘around` hook docs.
RSpec::Core::Hooks#around
# File rspec-core/lib/rspec/core/configuration.rb, line 1922 def around(scope=nil, *meta, &block) add_hook_to_existing_matching_groups(meta, scope) { |g| g.around(scope, *meta, &block) } super(scope, *meta, &block) end
Regexps used to exclude lines from backtraces.
Excludes lines from ruby (and jruby) source, installed gems, anything in any “bin” directory, and any of the RSpec libs (outside gem installs) by default.
You can modify the list via the getter, or replace it with the setter.
To override this behaviour and display a full backtrace, use ‘–backtrace` on the command line, in a `.rspec` file, or in the `rspec_options` attribute of RSpec’s rake task. @return [Array<Regexp>]
# File rspec-core/lib/rspec/core/configuration.rb, line 615 def backtrace_exclusion_patterns @backtrace_formatter.exclusion_patterns end
Set regular expressions used to exclude lines in backtrace. @param patterns [Array<Regexp>] set backtrace_formatter exclusion_patterns
# File rspec-core/lib/rspec/core/configuration.rb, line 621 def backtrace_exclusion_patterns=(patterns) @backtrace_formatter.exclusion_patterns = patterns end
Regexps used to include lines in backtraces.
Defaults to [Regexp.new Dir.getwd].
Lines that match an exclusion and an inclusion pattern will be included.
You can modify the list via the getter, or replace it with the setter. @return [Array<Regexp>]
# File rspec-core/lib/rspec/core/configuration.rb, line 634 def backtrace_inclusion_patterns @backtrace_formatter.inclusion_patterns end
Set regular expressions used to include lines in backtrace. @attr patterns [Array<Regexp>] set backtrace_formatter inclusion_patterns
# File rspec-core/lib/rspec/core/configuration.rb, line 640 def backtrace_inclusion_patterns=(patterns) @backtrace_formatter.inclusion_patterns = patterns end
Defines a ‘before` hook. See {Hooks#before} for full docs.
This method differs from {Hooks#before} in only one way: it supports the ‘:suite` scope. Hooks with the `:suite` scope will be run once before the first example of the entire suite is executed. Conditions passed along with `:suite` are effectively ignored.
@see prepend_before @see after @see append_after
RSpec::Core::Hooks#before
# File rspec-core/lib/rspec/core/configuration.rb, line 1843 def before(scope=nil, *meta, &block) handle_suite_hook(scope, meta) do @before_suite_hooks << Hooks::BeforeHook.new(block, {}) end || begin add_hook_to_existing_matching_groups(meta, scope) { |g| g.before(scope, *meta, &block) } super(scope, *meta, &block) end end
# File rspec-core/lib/rspec/core/configuration.rb, line 413 def bisect_runner=(value) if @bisect_runner_class && value != @bisect_runner raise "`config.bisect_runner = #{value.inspect}` can no longer take " \ "effect as the #{@bisect_runner.inspect} bisect runnner is already " \ "in use. This config setting must be set in a file loaded by a " \ "`--require` option (passed at the CLI or in a `.rspec` file) for " \ "it to have any effect." end @bisect_runner = value end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1962 def bisect_runner_class @bisect_runner_class ||= begin case bisect_runner when :fork RSpec::Support.require_rspec_core 'bisect/fork_runner' Bisect::ForkRunner when :shell RSpec::Support.require_rspec_core 'bisect/shell_runner' Bisect::ShellRunner else raise "Unsupported value for `bisect_runner` (#{bisect_runner.inspect}). " \ "Only `:fork` and `:shell` are supported." end end end
Check if color is enabled for a particular output. @param output [IO] an output stream to use, defaults to the current
`output_stream`
@return [Boolean]
# File rspec-core/lib/rspec/core/configuration.rb, line 847 def color_enabled?(output=output_stream) case color_mode when :on then true when :off then false else # automatic output_to_tty?(output) end end
The mode for determining whether to display output in color. One of:
-
:automatic - the output will be in color if the output is a TTY (the default)
-
:on - the output will be in color, whether or not the output is a TTY
-
:off - the output will not be in color
@see color_enabled? @return [Boolean]
# File rspec-core/lib/rspec/core/configuration.rb, line 839 def color_mode value_for(:color_mode) { @color_mode } end
@private
Used internally to extend the singleton class of a single example’s example group instance with modules using ‘include` and/or `extend`.
# File rspec-core/lib/rspec/core/configuration.rb, line 1468 def configure_example(example, example_hooks) example_hooks.register_global_singleton_context_hooks(example, hooks) singleton_group = example.example_group_instance.singleton_class # We replace the metadata so that SharedExampleGroupModule#included # has access to the example's metadata[:location]. singleton_group.with_replaced_metadata(example.metadata) do modules = @include_modules.items_for(example.metadata) modules.each do |mod| safe_include(mod, example.example_group_instance.singleton_class) end MemoizedHelpers.define_helpers_on(singleton_group) unless modules.empty? end end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1509 def configure_expectation_framework expectation_frameworks.each do |framework| RSpec::Core::ExampleGroup.include(framework) end end
@private
Used internally to extend a group with modules using ‘include`, `prepend` and/or `extend`.
# File rspec-core/lib/rspec/core/configuration.rb, line 1456 def configure_group(group) group.hooks.register_globals(group, hooks) configure_group_with group, @include_modules, :safe_include configure_group_with group, @extend_modules, :safe_extend configure_group_with group, @prepend_modules, :safe_prepend end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1504 def configure_mock_framework RSpec::Core::ExampleGroup.include(mock_framework) end
The formatter that will be used if no formatter has been set. Defaults to ‘progress’.
# File rspec-core/lib/rspec/core/configuration.rb, line 900 def default_formatter formatter_loader.default_formatter end
Sets a fallback formatter to use if none other has been set.
@example
RSpec.configure do |rspec| rspec.default_formatter = 'doc' end
# File rspec-core/lib/rspec/core/configuration.rb, line 911 def default_formatter=(value) formatter_loader.default_formatter = value end
# File rspec-core/lib/rspec/core/configuration.rb, line 122 def default_path=(path) project_source_dirs << path @default_path = path end
Defines a callback that can assign derived metadata values.
@param filters [Array<Symbol>, Hash] metadata filters that determine
which example or group metadata hashes the callback will be triggered for. If none are given, the callback will be run against the metadata hashes of all groups and examples.
@yieldparam metadata [Hash] original metadata hash from an example or
group. Mutate this in your block as needed.
@example
RSpec.configure do |config| # Tag all groups and examples in the spec/unit directory with # :type => :unit config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata| metadata[:type] = :unit end end
# File rspec-core/lib/rspec/core/configuration.rb, line 1767 def define_derived_metadata(*filters, &block) meta = Metadata.build_hash_from(filters) @derived_metadata_blocks.append(block, meta) end
Determines where deprecation warnings are printed. @param value [IO, String] IO to write to or filename to write to
# File rspec-core/lib/rspec/core/configuration.rb, line 148 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
@return [Boolean] Whether or not ruby deprecations are enabled.
# File rspec-core/lib/rspec/core/configuration.rb, line 1669 def deprecation_warnings? ::Warning[:deprecated] end
Sets the file path to use for persisting example statuses. Necessary for the ‘–only-failures` and `–next-failure` CLI options.
# File rspec-core/lib/rspec/core/configuration.rb, line 172 def example_status_persistence_file_path=(value) @example_status_persistence_file_path = value clear_values_derived_from_example_status_persistence_file_path end
Set pattern to match files to exclude. @attr value [String] the filename pattern to exclude spec files by
# File rspec-core/lib/rspec/core/configuration.rb, line 283 def exclude_pattern=(value) update_pattern_attr :exclude_pattern, value end
Returns the ‘exclusion_filter`. If none has been set, returns an empty hash.
# File rspec-core/lib/rspec/core/configuration.rb, line 1259 def exclusion_filter filter_manager.exclusions end
Clears and reassigns the ‘exclusion_filter`. Set to `nil` if you don’t want any exclusion filter at all.
### Warning
This overrides any exclusion filters/tags set on the command line or in configuration files.
# File rspec-core/lib/rspec/core/configuration.rb, line 1252 def exclusion_filter=(filter) meta = Metadata.build_hash_from([filter]) filter_manager.exclude_only meta end
Sets the expectation framework module(s) to be included in each example group.
‘frameworks` can be `:rspec`, `:test_unit`, `:minitest`, a custom module, or any combination thereof:
config.expect_with :rspec config.expect_with :test_unit config.expect_with :minitest config.expect_with :rspec, :minitest config.expect_with OtherExpectationFramework
RSpec will translate ‘:rspec`, `:minitest`, and `:test_unit` into the appropriate modules.
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
# File rspec-core/lib/rspec/core/configuration.rb, line 776 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.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
Delegates to expect_with(framework).
# File rspec-core/lib/rspec/core/configuration.rb, line 749 def expectation_framework=(framework) expect_with(framework) end
Returns the configured expectation framework adapter module(s)
# File rspec-core/lib/rspec/core/configuration.rb, line 737 def expectation_frameworks if @expectation_frameworks.empty? begin expect_with :rspec rescue LoadError expect_with Module.new end end @expectation_frameworks end
Exposes the current running example via the named helper method. RSpec 2.x exposed this via ‘example`, but in RSpec 3.0, the example is instead exposed via an arg yielded to `it`, `before`, `let`, etc. However, some extension gems (such as Capybara) depend on the RSpec 2.x’s ‘example` method, so this config option can be used to maintain compatibility.
@param method_name [Symbol] the name of the helper method
@example
RSpec.configure do |rspec| rspec.expose_current_running_example_as :example end RSpec.describe MyClass do before do # `example` can be used here because of the above config. do_something if example.metadata[:type] == "foo" end end
# File rspec-core/lib/rspec/core/configuration.rb, line 1723 def expose_current_running_example_as(method_name) ExposeCurrentExample.module_exec do extend RSpec::SharedContext let(method_name) { |ex| ex } end include ExposeCurrentExample end
Tells RSpec to extend example groups with ‘mod`. Methods defined in `mod` are exposed to example groups (not examples). Use `filters` to constrain the groups to extend.
Similar to ‘include`, but behavior is added to example groups, which are classes, rather than the examples, which are instances of those classes.
@example
module UiHelpers def run_in_browser # ... end end module PermissionHelpers def define_permissions # ... end end RSpec.configure do |config| config.extend(UiHelpers, :type => :request) config.extend(PermissionHelpers, :with_permissions, :type => :request) end describe "edit profile", :with_permissions, :type => :request do run_in_browser define_permissions it "does stuff in the client" do # ... end end
# File rspec-core/lib/rspec/core/configuration.rb, line 1408 def extend(mod, *filters) define_mixed_in_module(mod, filters, @extend_modules, :extend) do |group| safe_extend(mod, group) end end
@see fail_fast
# File rspec-core/lib/rspec/core/configuration.rb, line 194 def fail_fast=(value) case value when true, 'true' @fail_fast = true when false, 'false', 0 @fail_fast = false when nil @fail_fast = nil else @fail_fast = value.to_i if value.to_i == 0 raise ArgumentError, "Cannot set `RSpec.configuration.fail_fast` " \ "to `#{value.inspect}`. Only `true`, `" \ "`false`, `nil` and integers are valid " \ "values." end end end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 980 def files_or_directories_to_run=(*files) files = files.flatten if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty? files << default_path end @files_or_directories_to_run = files @files_to_run = nil end
The spec files RSpec will run. @return [Array] specified files about to run
# File rspec-core/lib/rspec/core/configuration.rb, line 993 def files_to_run @files_to_run ||= get_files_to_run(@files_or_directories_to_run) end
Adds {#backtrace_exclusion_patterns} that will filter lines from the named gems from backtraces.
@param gem_names [Array<String>] Names of the gems to filter
@example
RSpec.configure do |config| config.filter_gems_from_backtrace "rack", "rake" end
@note The patterns this adds will match the named gems in their common
locations (e.g. system gems, vendored with bundler, installed as a :git dependency with bundler, etc) but is not guaranteed to work for all possible gem locations. For example, if you have the gem source in a directory with a completely unrelated name, and use bundler's :path option, this will not filter it.
# File rspec-core/lib/rspec/core/configuration.rb, line 660 def filter_gems_from_backtrace(*gem_names) gem_names.each do |name| @backtrace_formatter.filter_gem(name) end end
Adds key/value pairs to the ‘exclusion_filter`. If `args` includes any symbols that are not part of the hash, each symbol is treated as a key in the hash with the value `true`.
### Note
Filters set using this method can be overridden from the command line or config files (e.g. ‘.rspec`).
@example
# Given this declaration. describe "something", :foo => 'bar' do # ... end # Any of the following will exclude that group. config.filter_run_excluding :foo => 'bar' config.filter_run_excluding :foo => /^ba/ config.filter_run_excluding :foo => lambda {|v| v == 'bar'} config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'} # Given a proc with an arity of 1, the lambda is passed the value # related to the key, e.g. config.filter_run_excluding :foo => lambda {|v| v == 'bar'} # Given a proc with an arity of 2, the lambda is passed the value # related to the key, and the metadata itself e.g. config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'} filter_run_excluding :foo # same as filter_run_excluding :foo => true
# File rspec-core/lib/rspec/core/configuration.rb, line 1239 def filter_run_excluding(*args) meta = Metadata.build_hash_from(args) filter_manager.exclude_with_low_priority meta static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta) end
Adds key/value pairs to the ‘inclusion_filter`. If `args` includes any symbols that are not part of the hash, each symbol is treated as a key in the hash with the value `true`.
### Note
Filters set using this method can be overridden from the command line or config files (e.g. ‘.rspec`).
@example
# Given this declaration. describe "something", :foo => 'bar' do # ... end # Any of the following will include that group. config.filter_run_including :foo => 'bar' config.filter_run_including :foo => /^ba/ config.filter_run_including :foo => lambda {|v| v == 'bar'} config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'} # Given a proc with an arity of 1, the lambda is passed the value # related to the key, e.g. config.filter_run_including :foo => lambda {|v| v == 'bar'} # Given a proc with an arity of 2, the lambda is passed the value # related to the key, and the metadata itself e.g. config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'} filter_run_including :foo # same as filter_run_including :foo => true
# File rspec-core/lib/rspec/core/configuration.rb, line 1165 def filter_run_including(*args) meta = Metadata.build_hash_from(args) filter_manager.include_with_low_priority meta static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta) end
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.
# File rspec-core/lib/rspec/core/configuration.rb, line 1181 def filter_run_when_matching(*args) when_first_matching_example_defined(*args) do filter_run(*args) end end
@private
Used to set higher priority option values from the command line.
# File rspec-core/lib/rspec/core/configuration.rb, line 510 def force(hash) ordering_manager.force(hash) @preferred_options.merge!(hash) return unless hash.key?(:example_status_persistence_file_path) clear_values_derived_from_example_status_persistence_file_path end
Formats the docstring output using the block provided.
@example
# This will strip the descriptions of both examples and example # groups. RSpec.configure do |config| config.format_docstrings { |s| s.strip } end
# File rspec-core/lib/rspec/core/configuration.rb, line 1547 def format_docstrings(&block) @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1552 def format_docstrings_block @format_docstrings_block ||= DEFAULT_FORMATTER end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 926 def formatter_loader @formatter_loader ||= Formatters::Loader.new(Reporter.new(self)) end
Returns a duplicate of the formatters currently loaded in the ‘FormatterLoader` for introspection.
Note as this is a duplicate, any mutations will be disregarded.
@return [Array] the formatters currently loaded
# File rspec-core/lib/rspec/core/configuration.rb, line 921 def formatters formatter_loader.formatters.dup end
Toggle full backtrace. @attr true_or_false [Boolean] toggle full backtrace display
# File rspec-core/lib/rspec/core/configuration.rb, line 826 def full_backtrace=(true_or_false) @backtrace_formatter.full_backtrace = true_or_false end
Check if full backtrace is enabled. @return [Boolean] is full backtrace enabled
# File rspec-core/lib/rspec/core/configuration.rb, line 820 def full_backtrace? @backtrace_formatter.full_backtrace? end
@return [Array] full description filter
# File rspec-core/lib/rspec/core/configuration.rb, line 874 def full_description filter.fetch :full_description, nil end
Run examples matching on ‘description` in all files to run. @param description [String, Regexp] the pattern to filter on
# File rspec-core/lib/rspec/core/configuration.rb, line 869 def full_description=(description) filter_run :full_description => Regexp.union(*Array(description).map { |d| Regexp.new(d) }) end
@private Holds the various registered hooks. Here we use a FilterableItemRepository implementation that is specifically optimized for the read/write patterns of the config object.
# File rspec-core/lib/rspec/core/configuration.rb, line 1946 def hooks @hooks ||= HookCollections.new(self, FilterableItemRepository::QueryOptimized) end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1495 def in_project_source_dir_regex regexes = project_source_dirs.map do |dir| /\A#{Regexp.escape(File.expand_path(dir))}\// end Regexp.union(regexes) end
Tells RSpec to include ‘mod` in example groups. Methods defined in `mod` are exposed to examples (not example groups). Use `filters` to constrain the groups or examples in which to include the module.
@example
module AuthenticationHelpers def login_as(user) # ... end end module PreferencesHelpers def preferences(user, preferences = {}) # ... end end module UserHelpers def users(username) # ... end end RSpec.configure do |config| config.include(UserHelpers) # included in all groups # included in examples with `:preferences` metadata config.include(PreferenceHelpers, :preferences) # included in examples with `:type => :request` metadata config.include(AuthenticationHelpers, :type => :request) # included in examples where the `:type` metadata matches a proc condition config.include(AuthenticationHelpers, :type => proc { |type, _metadata| [:request, :controller].include?(type) }) end describe "edit profile", :preferences, :type => :request do it "can be viewed by owning user" do login_as preferences(users(:jdoe), :lang => 'es') get "/profiles/jdoe" assert_select ".username", :text => 'jdoe' end end
@note Filtered module inclusions can also be applied to
individual examples that have matching metadata. Just like Ruby's object model is that every object has a singleton class which has only a single instance, RSpec's model is that every example has a singleton example group containing just the one example.
@see include_context @see extend @see prepend
# File rspec-core/lib/rspec/core/configuration.rb, line 1318 def include(mod, *filters) define_mixed_in_module(mod, filters, @include_modules, :include) do |group| safe_include(mod, group) end end
Tells RSpec to include the named shared example group in example groups. Use ‘filters` to constrain the groups or examples in which to include the example group.
@example
RSpec.shared_context "example admin user" do let(:admin_user) { create_user(:admin) } end RSpec.shared_context "example guest user" do let(:guest_user) { create_user(:guest) } end RSpec.configure do |config| config.include_context "example guest user", :type => :request config.include_context "example admin user", :admin, :type => :request end RSpec.describe "The admin page", :type => :request do it "can be viewed by admins", :admin do login_with admin_user get "/admin" expect(response).to be_ok end it "cannot be viewed by guests" do login_with guest_user get "/admin" expect(response).to be_forbidden end end
@note Filtered context inclusions can also be applied to
individual examples that have matching metadata. Just like Ruby's object model is that every object has a singleton class which has only a single instance, RSpec's model is that every example has a singleton example group containing just the one example.
@see include
# File rspec-core/lib/rspec/core/configuration.rb, line 1365 def include_context(shared_group_name, *filters) shared_module = world.shared_example_group_registry.find([:main], shared_group_name) include shared_module, *filters end
Returns the ‘inclusion_filter`. If none has been set, returns an empty hash.
# File rspec-core/lib/rspec/core/configuration.rb, line 1203 def inclusion_filter filter_manager.inclusions end
Clears and reassigns the ‘inclusion_filter`. Set to `nil` if you don’t want any inclusion filter at all.
### Warning
This overrides any inclusion filters/tags set on the command line or in configuration files.
# File rspec-core/lib/rspec/core/configuration.rb, line 1194 def inclusion_filter=(filter) meta = Metadata.build_hash_from([filter]) filter_manager.include_only meta end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 998 def last_run_statuses @last_run_statuses ||= Hash.new(UNKNOWN_STATUS).tap do |statuses| if (path = example_status_persistence_file_path) begin ExampleStatusPersister.load_from(path).inject(statuses) do |hash, example| status = example[:status] status = UNKNOWN_STATUS unless VALID_STATUSES.include?(status) hash[example.fetch(:example_id)] = status hash end rescue SystemCallError => e RSpec.warning "Could not read from #{path.inspect} (configured as " \ "`config.example_status_persistence_file_path`) due " \ "to a system error: #{e.inspect}. Please check that " \ "the config option is set to an accessible, valid " \ "file path", :call_site => nil end end end end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 860 def libs=(libs) libs.map do |lib| @libs.unshift lib $LOAD_PATH.unshift lib end end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1516 def load_spec_files # Note which spec files world is already aware of. # This is generally only needed for when the user runs # `ruby path/to/spec.rb` (and loads `rspec/autorun`) -- # in that case, the spec file was loaded by `ruby` and # isn't loaded by us here so we only know about it because # of an example group being registered in it. world.registered_example_group_files.each do |f| loaded_spec_files << f # the registered files are already expended absolute paths end files_to_run.uniq.each do |f| file = File.expand_path(f) load_file_handling_errors(:load, file) loaded_spec_files << file end @spec_files_loaded = true end
Returns the configured mock framework adapter module. @return [Symbol]
# File rspec-core/lib/rspec/core/configuration.rb, line 587 def mock_framework if @mock_framework.nil? begin mock_with :rspec rescue LoadError mock_with :nothing end end @mock_framework end
Delegates to mock_framework=(framework).
# File rspec-core/lib/rspec/core/configuration.rb, line 599 def mock_framework=(framework) mock_with framework end
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
# File rspec-core/lib/rspec/core/configuration.rb, line 704 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
Invokes block before defining an example group
# File rspec-core/lib/rspec/core/configuration.rb, line 1951 def on_example_group_definition(&block) on_example_group_definition_callbacks << block end
@api private Returns an array of blocks to call before defining an example group
# File rspec-core/lib/rspec/core/configuration.rb, line 1957 def on_example_group_definition_callbacks @on_example_group_definition_callbacks ||= [] end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 183 def only_failures_but_not_configured? only_failures? && !example_status_persistence_file_path end
Set the output stream for reporter. @attr value [IO, String] IO to write to or filename to write to, defaults to $stdout
# File rspec-core/lib/rspec/core/configuration.rb, line 253 def output_stream=(value) if @reporter && !value.equal?(@output_stream) warn "RSpec's reporter has already been initialized with " \ "#{output_stream.inspect} as the output stream, so your change to " \ "`output_stream` will be ignored. You should configure it earlier for " \ "it to take effect. (Called from #{CallerFilter.first_non_rspec_line})" else @output_stream = value output_wrapper.output = @output_stream end end
Set pattern to match files to load. @attr value [String] the filename pattern to filter spec files by
# File rspec-core/lib/rspec/core/configuration.rb, line 272 def pattern=(value) update_pattern_attr :pattern, value end
# File rspec-core/lib/rspec/core/configuration.rb, line 380 def pending_failure_output=(mode) raise ArgumentError, "`pending_failure_output` can be set to :full, :no_backtrace, " \ "or :skip" unless [:full, :no_backtrace, :skip].include?(mode) @pending_failure_output = mode end
Tells RSpec to prepend example groups with ‘mod`. Methods defined in `mod` are exposed to examples (not example groups). Use `filters` to constrain the groups in which to prepend the module.
Similar to ‘include`, but module is included before the example group’s class in the ancestor chain.
@example
module OverrideMod def override_me "overridden" end end RSpec.configure do |config| config.prepend(OverrideMod, :method => :prepend) end describe "overriding example's class", :method => :prepend do it "finds the user" do self.class.class_eval do def override_me end end override_me # => "overridden" # ... end end
# File rspec-core/lib/rspec/core/configuration.rb, line 1446 def prepend(mod, *filters) define_mixed_in_module(mod, filters, @prepend_modules, :prepend) do |group| safe_prepend(mod, group) end end
Adds ‘block` to the start of the list of `before` blocks in the same scope (`:example`, `:context`, or `:suite`), in contrast to {#before}, which adds the hook to the end of the list.
See {Hooks#before} for full ‘before` hook docs.
This method differs from {Hooks#prepend_before} in only one way: it supports the ‘:suite` scope. Hooks with the `:suite` scope will be run once before the first example of the entire suite is executed. Conditions passed along with `:suite` are effectively ignored.
@see before @see after @see append_after
RSpec::Core::Hooks#prepend_before
# File rspec-core/lib/rspec/core/configuration.rb, line 1867 def prepend_before(scope=nil, *meta, &block) handle_suite_hook(scope, meta) do @before_suite_hooks.unshift Hooks::BeforeHook.new(block, {}) end || begin add_hook_to_existing_matching_groups(meta, scope) { |g| g.prepend_before(scope, *meta, &block) } super(scope, *meta, &block) end end
@api private
Defaults ‘profile_examples` to 10 examples when `@profile_examples` is `true`.
# File rspec-core/lib/rspec/core/configuration.rb, line 970 def profile_examples profile = value_for(:profile_examples) { @profile_examples } if profile && !profile.is_a?(Integer) 10 else profile end end
Turns deprecation warnings into errors, in order to surface the full backtrace of the call site. This can be useful when you need more context to address a deprecation than the single-line call site normally provided.
@example
RSpec.configure do |rspec| rspec.raise_errors_for_deprecations! end
# File rspec-core/lib/rspec/core/configuration.rb, line 1746 def raise_errors_for_deprecations! self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new end
Turns RSpec warnings into errors. This can be useful when you want RSpec to run in a ‘strict’ no warning situation. (Note this does not capture or raise on Ruby warnings).
@example
RSpec.configure do |rspec| rspec.raise_on_warning = true end
# File rspec-core/lib/rspec/core/configuration.rb, line 1693 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
@return [RSpec::Core::Reporter] the currently configured reporter
# File rspec-core/lib/rspec/core/configuration.rb, line 953 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
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1485 def requires=(paths) directories = ['lib', default_path].select { |p| File.directory? p } RSpec::Core::RubyProject.add_to_load_path(*directories) paths.each { |path| load_file_handling_errors(:require, path) @requires << path } end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 519 def reset @spec_files_loaded = false reset_reporter end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 532 def reset_filters self.filter_manager = FilterManager.new filter_manager.include_only( Metadata.deep_hash_dup(static_config_filter_manager.inclusions.rules) ) filter_manager.exclude_only( Metadata.deep_hash_dup(static_config_filter_manager.exclusions.rules) ) end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 525 def reset_reporter @reporter = nil @formatter_loader = nil @output_wrapper = nil end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1035 def spec_files_with_failures @spec_files_with_failures ||= last_run_statuses.inject(Set.new) do |files, (id, status)| files << Example.parse_id(id).first if status == FAILED_STATUS files end.to_a end
Set Ruby warnings. ‘:deprecations_only` is recommended, but may be too noisy due to dependencies. Can be set to `:all` or `:none` to show all warnings or none of them.
# File rspec-core/lib/rspec/core/configuration.rb, line 1648 def warnings=(value) case value when :none @warnings = :none $VERBOSE = false ::Warning[:deprecated] = false when :all @warnings = :all $VERBOSE = true ::Warning[:deprecated] = true when :deprecations_only @warnings = :deprecations_only $VERBOSE = false ::Warning[:deprecated] = true else raise "Unsupported value for `warnings` (#{value.inspect}). " \ "Only `:none`, `:all` and `:deprecations_only` are supported." end end
@return [Boolean] Whether or not ruby warnings are enabled.
# File rspec-core/lib/rspec/core/configuration.rb, line 1677 def warnings? $VERBOSE end
Defines a callback that runs after the first example with matching metadata is defined. If no examples are defined with matching metadata, it will not get called at all.
This can be used to ensure some setup is performed (such as bootstrapping a DB or loading a specific file that adds significantly to the boot time) if needed (as indicated by the presence of an example with matching metadata) but avoided otherwise.
@example
RSpec.configure do |config| config.when_first_matching_example_defined(:db) do # Load a support file that does some heavyweight setup, # including bootstrapping the DB, but only if we have loaded # any examples tagged with `:db`. require 'support/db' end end
# File rspec-core/lib/rspec/core/configuration.rb, line 1790 def when_first_matching_example_defined(*filters) specified_meta = Metadata.build_hash_from(filters) callback = lambda do |example_or_group_meta| # Example groups do not have `:example_group` metadata # (instead they have `:parent_example_group` metadata). return unless example_or_group_meta.key?(:example_group) # Ensure the callback only fires once. @derived_metadata_blocks.delete(callback, specified_meta) yield end @derived_metadata_blocks.append(callback, specified_meta) end
@private
# File rspec-core/lib/rspec/core/configuration.rb, line 1928 def with_suite_hooks return yield if dry_run? begin RSpec.current_scope = :before_suite_hook run_suite_hooks("a `before(:suite)` hook", @before_suite_hooks) yield ensure RSpec.current_scope = :after_suite_hook run_suite_hooks("an `after(:suite)` hook", @after_suite_hooks) RSpec.current_scope = :suite end end