class RSpec::Core::Configuration

Stores runtime configuration information.

@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(:each)  { log_in_as :authorized }
  c.around(:each)  { |ex| Database.transaction(&ex) }
end

@see RSpec.configure @see Hooks

Constants

DEFAULT_BACKTRACE_PATTERNS

Attributes

filter_manager[RW]

@private

Public Class Methods

add_setting(name, opts={}) click to toggle source

@private

Invoked by the `::add_setting` instance method. Use that method on a `Configuration` instance rather than this class method.

# File lib/rspec/core/configuration.rb, line 61
def self.add_setting(name, opts={})
  raise "Use the instance add_setting method if you want to set a default" if opts.has_key?(:default)
  if opts[:alias]
    deprecate_alias_key
    define_aliases(opts[:alias], name)
  else
    attr_writer name
    define_reader name
    define_predicate_for name
  end
  [opts[:alias_with]].flatten.compact.each do |alias_name|
    define_aliases(name, alias_name)
  end
end
define_aliases(name, alias_name) click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 46
def self.define_aliases(name, alias_name)
  alias_method alias_name, name
  alias_method "#{alias_name}=", "#{name}="
  define_predicate_for alias_name
end
define_predicate_for(*names) click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 53
def self.define_predicate_for(*names)
  names.each {|name| alias_method "#{name}?", name}
end
define_reader(name) click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 29
      def self.define_reader(name)
        eval "          def #{name}
            value_for(#{name.inspect}, defined?(@#{name}) ? @#{name} : nil)
          end
"
      end
deprecate_alias_key() click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 38
      def self.deprecate_alias_key
        RSpec.warn_deprecation "The :alias option to add_setting is deprecated. Use :alias_with on the original setting instead.
Called from #{caller(0)[5]}
"
      end
new() click to toggle source
# File lib/rspec/core/configuration.rb, line 179
def initialize
  @expectation_frameworks = []
  @include_or_extend_modules = []
  @mock_framework = nil
  @files_to_run = []
  @formatters = []
  @color = false
  @pattern = '**/*_spec.rb'
  @failure_exit_code = 1
  @backtrace_clean_patterns = DEFAULT_BACKTRACE_PATTERNS.dup
  @default_path = 'spec'
  @filter_manager = FilterManager.new
  @preferred_options = {}
  @seed = srand % 0xFFFF
end

Public Instance Methods

add_formatter(formatter_to_use, path=nil) click to toggle source

@overload #add_formatter(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 path to a file that contains that class definition, but you should consider that a private api that may change at any time without notice.

# File lib/rspec/core/configuration.rb, line 478
def add_formatter(formatter_to_use, path=nil)
  formatter_class =
    built_in_formatter(formatter_to_use) ||
    custom_formatter(formatter_to_use) ||
    (raise ArgumentError, "Formatter '#{formatter_to_use}' unknown - maybe you meant 'documentation' or 'progress'?.")

  formatters << formatter_class.new(path ? file_at(path) : output)
end
Also aliased as: formatter=
add_setting(name, opts={}) click to toggle source

@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 %x: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 lib/rspec/core/configuration.rb, line 248
def add_setting(name, opts={})
  default = opts.delete(:default)
  (class << self; self; end).class_eval do
    add_setting(name, opts)
  end
  send("#{name}=", default) if default
end
alias_example_to(new_name, *args) click to toggle source

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

@example

alias_example_to :pending, :pending => true

# 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
# File lib/rspec/core/configuration.rb, line 528
def alias_example_to(new_name, *args)
  extra_options = build_metadata_hash_from(args)
  RSpec::Core::ExampleGroup.alias_example_to(new_name, extra_options)
end
alias_it_behaves_like_to(new_name, report_label = '') click to toggle source

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

Example:

alias_it_behaves_like_to(:it_has_behavior, 'has behavior:')

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
# File lib/rspec/core/configuration.rb, line 554
def alias_it_behaves_like_to(new_name, report_label = '')
  RSpec::Core::ExampleGroup.alias_it_behaves_like_to(new_name, report_label)
end
alias_it_should_behave_like_to(new_name, report_label = '') click to toggle source
cleaned_from_backtrace?(line) click to toggle source

Used by formatters to ask whether a backtrace line should be displayed or not, based on the line matching any `backtrace_clean_patterns`.

# File lib/rspec/core/configuration.rb, line 258
def cleaned_from_backtrace?(line)
  # TODO (David 2011-12-25) why are we asking the configuration to do
  # stuff? Either use the patterns directly or enapsulate the filtering
  # in a BacktraceCleaner object.
  backtrace_clean_patterns.any? { |regex| line =~ regex }
end
color() click to toggle source
# File lib/rspec/core/configuration.rb, line 408
def color
  return false unless output_to_tty?
  value_for(:color, @color)
end
Also aliased as: color_enabled
color=(bool) click to toggle source
# File lib/rspec/core/configuration.rb, line 413
def color=(bool)
  if bool
    @color = true
    if RSpec.windows_os? and not ENV['ANSICON']
      warn "You must use ANSICON 1.31 or later (http://adoxa.110mb.com/ansicon/) to use colour on Windows"
      @color = false
    end
  end
end
Also aliased as: color_enabled=
color_enabled() click to toggle source

TODO - deprecate #color_enabled - probably not until the last 2.x release before 3.0

Alias for: color
color_enabled=(bool) click to toggle source
Alias for: color=
configure_expectation_framework() click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 772
def configure_expectation_framework
  expectation_frameworks.each do |framework|
    RSpec::Core::ExampleGroup.send(:include, framework)
  end
end
configure_group(group) click to toggle source

@private

Used internally to extend a group with modules using `include` and/or `extend`.

# File lib/rspec/core/configuration.rb, line 743
def configure_group(group)
  include_or_extend_modules.each do |include_or_extend, mod, filters|
    next unless filters.empty? || group.any_apply?(filters)
    send("safe_#{include_or_extend}", mod, group)
  end
end
configure_mock_framework() click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 767
def configure_mock_framework
  RSpec::Core::ExampleGroup.send(:include, mock_framework)
end
debug=(bool) click to toggle source
# File lib/rspec/core/configuration.rb, line 437
      def debug=(bool)
        return unless bool
        begin
          require 'ruby-debug'
          Debugger.start
        rescue LoadError => e
          raise "
#{'*'*50}
#{e.message}

If you have it installed as a ruby gem, then you need to either require
'rubygems' or configure the RUBYOPT environment variable with the value
'rubygems'.

#{e.backtrace.join("\n")}
#{'*'*50}
"
        end
      end
exclusion_filter() click to toggle source

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

# File lib/rspec/core/configuration.rb, line 666
def exclusion_filter
  filter_manager.exclusions
end
exclusion_filter=(filter) click to toggle source

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 lib/rspec/core/configuration.rb, line 660
def exclusion_filter=(filter)
  filter_manager.exclude! build_metadata_hash_from([filter])
end
expect_with(*frameworks) { |first.configuration| ... } click to toggle source

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

`frameworks` can be `:rspec`, `:stdlib`, a custom module, or any combination thereof:

config.expect_with :rspec
config.expect_with :stdlib
config.expect_with :rspec, :stdlib
config.expect_with OtherExpectationFramework

RSpec will translate `:rspec` and `:stdlib` 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
# File lib/rspec/core/configuration.rb, line 374
def expect_with(*frameworks)
  modules = frameworks.map do |framework|
    case framework
    when Module
      framework
    when :rspec
      require 'rspec/expectations'
      self.expecting_with_rspec = true
      ::RSpec::Matchers
    when :stdlib
      require 'test/unit/assertions'
      ::Test::Unit::Assertions
    else
      raise ArgumentError, "#{framework.inspect} is not supported"
    end
  end

  if (modules - @expectation_frameworks).any?
    assert_no_example_groups_defined(:expect_with)
  end

  if block_given?
    raise "expect_with only accepts a block with a single argument. Call expect_with #{modules.length} times, once with each argument, instead." if modules.length > 1
    raise "#{modules.first} must respond to `configuration` so that expect_with can yield it." unless modules.first.respond_to?(:configuration)
    yield modules.first.configuration
  end

  @expectation_frameworks.push(*modules)
end
expectation_framework=(framework) click to toggle source

Delegates to #expect_with(framework)

# File lib/rspec/core/configuration.rb, line 348
def expectation_framework=(framework)
  expect_with(framework)
end
expectation_frameworks() click to toggle source

Returns the configured expectation framework adapter module(s)

# File lib/rspec/core/configuration.rb, line 342
def expectation_frameworks
  expect_with :rspec if @expectation_frameworks.empty?
  @expectation_frameworks
end
extend(mod, *filters) click to toggle source

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

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 include

# File lib/rspec/core/configuration.rb, line 735
def extend(mod, *filters)
  include_or_extend_modules << [:extend, mod, build_metadata_hash_from(filters)]
end
files_or_directories_to_run=(*files) click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 501
def files_or_directories_to_run=(*files)
  files = files.flatten
  files << default_path if command == 'rspec' && default_path && files.empty?
  self.files_to_run = get_files_to_run(files)
end
filter() click to toggle source
Alias for: inclusion_filter
filter=(filter) click to toggle source
Alias for: inclusion_filter=
filter_run(*args) click to toggle source
filter_run_excluding(*args) click to toggle source

Adds key/value pairs to the `#exclusion_filter`. If the `treat_symbols_as_metadata_keys_with_true_values` config option is set to true and `args` excludes any symbols that are not part of a 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 => %r^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'}

# with treat_symbols_as_metadata_keys_with_true_values = true
filter_run_excluding :foo # same as filter_run_excluding :foo => true
# File lib/rspec/core/configuration.rb, line 649
def filter_run_excluding(*args)
  filter_manager.exclude_with_low_priority build_metadata_hash_from(args)
end
filter_run_including(*args) click to toggle source

Adds key/value pairs to the `#inclusion_filter`. If the `treat_symbols_as_metadata_keys_with_true_values` config option is set to true and `args` includes any symbols that are not part of a 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 => %r^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'}

# with treat_symbols_as_metadata_keys_with_true_values = true
filter_run_including :foo # same as filter_run_including :foo => true
# File lib/rspec/core/configuration.rb, line 591
def filter_run_including(*args)
  filter_manager.include_with_low_priority build_metadata_hash_from(args)
end
Also aliased as: filter_run
force(hash) click to toggle source

@private

Used to set higher priority option values from the command line.

# File lib/rspec/core/configuration.rb, line 198
def force(hash)
  if hash.has_key?(:seed)
    hash[:order], hash[:seed] = order_and_seed_from_seed(hash[:seed])
  elsif hash.has_key?(:order)
    set_order_and_seed(hash)
  end
  @preferred_options.merge!(hash)
end
formatter=(formatter_to_use, path=nil) click to toggle source
Alias for: add_formatter
formatters() click to toggle source
# File lib/rspec/core/configuration.rb, line 489
def formatters
  @formatters ||= []
end
full_backtrace=(true_or_false) click to toggle source
# File lib/rspec/core/configuration.rb, line 404
def full_backtrace=(true_or_false)
  @backtrace_clean_patterns = true_or_false ? [] : DEFAULT_BACKTRACE_PATTERNS
end
full_description=(description) click to toggle source
# File lib/rspec/core/configuration.rb, line 463
def full_description=(description)
  filter_run :full_description => Regexp.union(*Array(description).map {|d| Regexp.new(d) })
end
include(mod, *filters) click to toggle source

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 in which to include the module.

@example

module AuthenticationHelpers
  def login_as(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
    login_as users(:jdoe)
    get "/profiles/jdoe"
    assert_select ".username", :text => 'jdoe'
  end
end

@see extend

# File lib/rspec/core/configuration.rb, line 702
def include(mod, *filters)
  include_or_extend_modules << [:include, mod, build_metadata_hash_from(filters)]
end
inclusion_filter() click to toggle source

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

# File lib/rspec/core/configuration.rb, line 612
def inclusion_filter
  filter_manager.inclusions
end
Also aliased as: filter
inclusion_filter=(filter) click to toggle source

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 lib/rspec/core/configuration.rb, line 604
def inclusion_filter=(filter)
  filter_manager.include! build_metadata_hash_from([filter])
end
Also aliased as: filter=
libs=(libs) click to toggle source
# File lib/rspec/core/configuration.rb, line 429
def libs=(libs)
  libs.map {|lib| $LOAD_PATH.unshift lib}
end
line_numbers=(line_numbers) click to toggle source

Run examples defined on `line_numbers` in all files to run.

# File lib/rspec/core/configuration.rb, line 459
def line_numbers=(line_numbers)
  filter_run :line_numbers => line_numbers.map{|l| l.to_i}
end
load_spec_files() click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 779
def load_spec_files
  files_to_run.uniq.map {|f| load File.expand_path(f) }
  raise_if_rspec_1_is_loaded
end
mock_framework() click to toggle source

Returns the configured mock framework adapter module

# File lib/rspec/core/configuration.rb, line 266
def mock_framework
  mock_with :rspec unless @mock_framework
  @mock_framework
end
mock_framework=(framework) click to toggle source

Delegates to #mock_framework=(framework)

# File lib/rspec/core/configuration.rb, line 272
def mock_framework=(framework)
  mock_with framework
end
mock_with(framework) { |configuration| ... } click to toggle source

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. 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 lib/rspec/core/configuration.rb, line 305
def mock_with(framework)
  framework_module = case framework
  when Module
    framework
  when String, Symbol
    require case framework.to_s
            when %rrspec/
              'rspec/core/mocking/with_rspec'
            when %rmocha/
              'rspec/core/mocking/with_mocha'
            when %rrr/
              'rspec/core/mocking/with_rr'
            when %rflexmock/
              'rspec/core/mocking/with_flexmock'
            else
              'rspec/core/mocking/with_absolutely_nothing'
            end
    RSpec::Core::MockFrameworkAdapter
  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
order=(type) click to toggle source

@api

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

# File lib/rspec/core/configuration.rb, line 794
def order=(type)
  order_and_seed_from_order(type)
end
randomize?() click to toggle source
# File lib/rspec/core/configuration.rb, line 798
def randomize?
  order.to_s.match(%rrand/)
end
reporter() click to toggle source
# File lib/rspec/core/configuration.rb, line 493
def reporter
  @reporter ||= begin
                  add_formatter('progress') if formatters.empty?
                  Reporter.new(*formatters)
                end
end
requires=(paths) click to toggle source
# File lib/rspec/core/configuration.rb, line 433
def requires=(paths)
  paths.map {|path| require path}
end
reset() click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 208
def reset
  @reporter = nil
  @formatters.clear
end
safe_extend(mod, host) click to toggle source
# File lib/rspec/core/configuration.rb, line 757
def safe_extend(mod, host)
  host.extend(mod) unless (class << host; self; end) < mod
end
safe_include(mod, host) click to toggle source

@private

# File lib/rspec/core/configuration.rb, line 751
def safe_include(mod, host)
  host.send(:include,mod) unless host < mod
end
seed=(seed) click to toggle source

@api

Sets the seed value and sets `order='rand'`

# File lib/rspec/core/configuration.rb, line 787
def seed=(seed)
  order_and_seed_from_seed(seed)
end