class RSpec::Core::Configuration
@see Hooks
@see RSpec.configure
end
c.around(:each) { |ex| Database.transaction(&ex) }
c.before(:each) { log_in_as :authorized }
c.before(:suite) { establish_connection }
RSpec.configure do |c|
@example Hooks
end
c.default_path = ‘behavior’
c.drb_port = 1234
c.drb = true
RSpec.configure do |c|
@example Standard settings
in ‘~/.rspec` can be overridden by an option in `.rspec-local`).
variable (listed in lowest to highest precedence; for example, an option
`.rspec-local`, command line switches, and the `SPEC_OPTS` environment
Configuration options are loaded from `~/.rspec`, `.rspec`,
Stores runtime configuration information.
def self.add_setting(name, opts={})
- Private: -
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
def self.define_aliases(name, alias_name)
- Private: -
def self.define_aliases(name, alias_name) alias_method alias_name, name alias_method "#{alias_name}=", "#{name}=" define_predicate_for alias_name end
def self.define_predicate_for(*names)
- Private: -
def self.define_predicate_for(*names) names.each {|name| alias_method "#{name}?", name} end
def self.define_reader(name)
- Private: -
def self.define_reader(name) define_method(name) do variable = instance_variable_defined?("@#{name}") ? instance_variable_get("@#{name}") : nil value_for(name, variable) end end
def self.deprecate_alias_key
- Private: -
def self.deprecate_alias_key RSpec.deprecate("add_setting with :alias option", :replacement => ":alias_with") end
def add_formatter(formatter_to_use, *paths)
-
add_formatter(formatter)
def add_formatter(formatter_to_use, *paths) 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'?.") paths << output if paths.empty? formatters << formatter_class.new(*paths.map {|p| String === p ? file_at(p) : p}) end
def add_setting(name, opts={})
(**opts)-
:alias_with(Symbol) -- -
:default(Symbol) --
Overloads:
-
add_setting(name, opts) -
add_setting(name)
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
def alias_example_to(new_name, *args)
end
thing = Thing.new
it "does something", :pending => true do
describe Thing do
# ... which is the equivalent of
end
end
thing = Thing.new
pending "does something" do
describe Thing do
# This lets you do this:
alias_example_to :pending, :pending => true
@example
`args`. Used internally to add variants of `example` like `pending`:
Creates a method that delegates to `example` including the submitted
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
def alias_it_behaves_like_to(new_name, report_label = '')
has behavior: sortability
Entity
which is reported in the output as:
end
end
let(:sortable) { Entity.new }
it_has_behavior 'sortability' do
describe Entity do
allows the user to include a shared example group like:
alias_it_behaves_like_to(:it_has_behavior, 'has behavior:')
Example:
employed when including shared examples.
language (like "it_has_behavior" or "it_behaves_like") to be
Define an alias for it_should_behave_like that allows different
def alias_it_behaves_like_to(new_name, report_label = '') RSpec::Core::ExampleGroup.alias_it_behaves_like_to(new_name, report_label) end
def assert_no_example_groups_defined(config_option)
def assert_no_example_groups_defined(config_option) if RSpec.world.example_groups.any? raise MustBeConfiguredBeforeExampleGroupsError.new( "RSpec's #{config_option} configuration option must be configured before " + "any example groups are defined, but you have already defined a group." ) end end
def backtrace_clean_patterns
`--backtrace`on the command line, in a `.rspec` file, or in the
To override this behaviour and display a full backtrace, use
getter
One can replace the list by using the setter or modify it through the
Defaults to RSpec::Core::BacktraceCleaner::DEFAULT_EXCLUSION_PATTERNS
Configuration#backtrace_exclusion_patterns instead
The patterns to discard from backtraces. Deprecated, use
def backtrace_clean_patterns RSpec.deprecate("RSpec::Core::Configuration#backtrace_clean_patterns", :replacement => "RSpec::Core::Configuration#backtrace_exclusion_patterns") @backtrace_cleaner.exclusion_patterns end
def backtrace_clean_patterns=(patterns)
def backtrace_clean_patterns=(patterns) RSpec.deprecate("RSpec::Core::Configuration#backtrace_clean_patterns", :replacement => "RSpec::Core::Configuration#backtrace_exclusion_patterns") @backtrace_cleaner.exclusion_patterns = patterns end
def backtrace_exclusion_patterns
`--backtrace`on the command line, in a `.rspec` file, or in the
To override this behaviour and display a full backtrace, use
getter
One can replace the list by using the setter or modify it through the
Defaults to RSpec::Core::BacktraceCleaner::DEFAULT_EXCLUSION_PATTERNS
The patterns to discard from backtraces.
def backtrace_exclusion_patterns @backtrace_cleaner.exclusion_patterns end
def backtrace_exclusion_patterns=(patterns)
def backtrace_exclusion_patterns=(patterns) @backtrace_cleaner.exclusion_patterns = patterns end
def backtrace_inclusion_patterns
One can replace the list by using the setter or modify it through the
matches any of the exclusion patterns. Otherwise it defaults to empty.
Defaults to [Regexp.new Dir.getwd] if the current working directory
The patterns to always include to backtraces.
def backtrace_inclusion_patterns @backtrace_cleaner.inclusion_patterns end
def backtrace_inclusion_patterns=(patterns)
def backtrace_inclusion_patterns=(patterns) @backtrace_cleaner.inclusion_patterns = patterns end
def built_in_formatter(key)
def built_in_formatter(key) case key.to_s when 'd', 'doc', 'documentation', 's', 'n', 'spec', 'nested' require 'rspec/core/formatters/documentation_formatter' RSpec::Core::Formatters::DocumentationFormatter when 'h', 'html' require 'rspec/core/formatters/html_formatter' RSpec::Core::Formatters::HtmlFormatter when 't', 'textmate' require 'rspec/core/formatters/text_mate_formatter' RSpec::Core::Formatters::TextMateFormatter when 'p', 'progress' require 'rspec/core/formatters/progress_formatter' RSpec::Core::Formatters::ProgressFormatter when 'j', 'json' require 'rspec/core/formatters/json_formatter' RSpec::Core::Formatters::JsonFormatter end end
def built_in_orderer?(block)
def built_in_orderer?(block) [DEFAULT_ORDERING, RANDOM_ORDERING].include?(block) end
def color(output=output_stream)
def color(output=output_stream) # rspec's built-in formatters all call this with the output argument, # but defaulting to output_stream for backward compatibility with # formatters in extension libs return false unless output_to_tty?(output) value_for(:color, @color) end
def color=(bool)
def color=(bool) if bool if RSpec.windows_os? and not ENV['ANSICON'] warn "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 end
def command
def command $0.split(File::SEPARATOR).last end
def configure_expectation_framework
- Private: -
def configure_expectation_framework expectation_frameworks.each do |framework| RSpec::Core::ExampleGroup.send(:include, framework) end end
def configure_group(group)
- Private: -
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
def configure_mock_framework
- Private: -
def configure_mock_framework RSpec::Core::ExampleGroup.send(:include, mock_framework) end
def custom_formatter(formatter_ref)
def custom_formatter(formatter_ref) if Class === formatter_ref formatter_ref elsif string_const?(formatter_ref) begin eval(formatter_ref) rescue NameError require path_for(formatter_ref) eval(formatter_ref) end end end
def debug=(bool)
def debug=(bool) return unless bool begin require 'ruby-debug' Debugger.start rescue LoadError => e raise <<-EOM 50} ssage} have it installed as a ruby gem, then you need to either require ems' or configure the RUBYOPT environment variable with the value ems'. cktrace.join("\n")} 50} end end
def debug?
def debug? !!defined?(Debugger) end
def example_ordering_block
- Private: -
def example_ordering_block @example_ordering_block ||= DEFAULT_ORDERING end
def exclusion_filter
Returns the `exclusion_filter`. If none has been set, returns an empty
def exclusion_filter filter_manager.exclusions end
def exclusion_filter=(filter)
This overrides any exclusion filters/tags set on the command line or in
### Warning
want any exclusion filter at all.
Clears and reassigns the `exclusion_filter`. Set to `nil` if you don't
def exclusion_filter=(filter) filter_manager.exclude! build_metadata_hash_from([filter]) end
def expect_with(*frameworks)
custom_config.custom_setting = true
config.expect_with OtherExpectationFramework do |custom_config|
yield the `configuration` object if given a block:
If the module responds to `configuration`, `expect_with` will
## Configuration
modules.
RSpec will translate `:rspec` and `:stdlib` into the appropriate
config.expect_with OtherExpectationFramework
config.expect_with :rspec, :stdlib
config.expect_with :stdlib
config.expect_with :rspec
combination thereof:
`frameworks` can be `:rspec`, `:stdlib`, a custom module, or any
group.
Sets the expectation framework module(s) to be included in each example
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
def expectation_framework=(framework)
def expectation_framework=(framework) expect_with(framework) end
def expectation_frameworks
def expectation_frameworks expect_with :rspec if @expectation_frameworks.empty? @expectation_frameworks end
def extend(mod, *filters)
- See: #include -
def extend(mod, *filters) include_or_extend_modules << [:extend, mod, build_metadata_hash_from(filters)] end
def extract_location(path)
def extract_location(path) if path =~ /^(.*?)((?:\:\d+)+)$/ path, lines = $1, $2[1..-1].split(":").map{|n| n.to_i} filter_manager.add_location path, lines end path end
def file_at(path)
def file_at(path) FileUtils.mkdir_p(File.dirname(path)) File.new(path, 'w') end
def files_or_directories_to_run=(*files)
- Private: -
def files_or_directories_to_run=(*files) files = files.flatten files << default_path if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty? self.files_to_run = get_files_to_run(files) end
def filter_run_excluding(*args)
# with treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
# and the metadata itself e.g.
# given a proc with an arity of 2, the lambda is passed the value related to the key,
config.filter_run_excluding :foo => lambda {|v| v == '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,m| m[:foo] == 'bar'}
config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
config.filter_run_excluding :foo => /^ba/
config.filter_run_excluding :foo => 'bar'
# any of the following will exclude that group
end
# ...
describe "something", :foo => 'bar' do
# given this declaration
@example
or config files (e.g. `.rspec`).
Filters set using this method can be overridden from the command line
### Note
each symbol is treated as a key in the hash with the value `true`.
to true and `args` excludes any symbols that are not part of a hash,
`treat_symbols_as_metadata_keys_with_true_values` config option is set
Adds key/value pairs to the `exclusion_filter`. If the
def filter_run_excluding(*args) filter_manager.exclude_with_low_priority build_metadata_hash_from(args) end
def filter_run_including(*args)
# with treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
# and the metadata itself e.g.
# given a proc with an arity of 2, the lambda is passed the value related to the key,
config.filter_run_including :foo => lambda {|v| v == '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,m| m[:foo] == 'bar'}
config.filter_run_including :foo => lambda {|v| v == 'bar'}
config.filter_run_including :foo => /^ba/
config.filter_run_including :foo => 'bar'
# any of the following will include that group
end
# ...
describe "something", :foo => 'bar' do
# given this declaration
@example
or config files (e.g. `.rspec`).
Filters set using this method can be overridden from the command line
### Note
each symbol is treated as a key in the hash with the value `true`.
to true and `args` includes any symbols that are not part of a hash,
`treat_symbols_as_metadata_keys_with_true_values` config option is set
Adds key/value pairs to the `inclusion_filter`. If the
def filter_run_including(*args) filter_manager.include_with_low_priority build_metadata_hash_from(args) end
def force(hash)
- Private: -
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) self.warnings = value_for :warnings, nil end
def format_docstrings(&block)
config.format_docstrings { |s| s.strip }
RSpec.configure do |config|
# This will strip the descriptions of both examples and example groups.
@example
Formats the docstring output using the block provided.
def format_docstrings(&block) @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER end
def format_docstrings_block
- Private: -
def format_docstrings_block @format_docstrings_block ||= DEFAULT_FORMATTER end
def formatters
def formatters @formatters ||= [] end
def full_backtrace=(true_or_false)
def full_backtrace=(true_or_false) @backtrace_cleaner.full_backtrace = true_or_false end
def full_backtrace?
def full_backtrace? @backtrace_cleaner.full_backtrace? end
def full_description
def full_description filter.fetch :full_description, nil end
def full_description=(description)
def full_description=(description) filter_run :full_description => Regexp.union(*Array(description).map {|d| Regexp.new(d) }) end
def gather_directories(path)
def gather_directories(path) stripped = "{#{pattern.gsub(/\s*,\s*/, ',')}}" files = pattern =~ /^#{Regexp.escape path}/ ? Dir[stripped] : Dir["#{path}/#{stripped}"] files.sort end
def get_files_to_run(paths)
def get_files_to_run(paths) paths.map do |path| path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR File.directory?(path) ? gather_directories(path) : extract_location(path) end.flatten.sort end
def group_ordering_block
- Private: -
def group_ordering_block @group_ordering_block ||= DEFAULT_ORDERING end
def include(mod, *filters)
- See: #extend -
def include(mod, *filters) include_or_extend_modules << [:include, mod, build_metadata_hash_from(filters)] end
def inclusion_filter
Returns the `inclusion_filter`. If none has been set, returns an empty
def inclusion_filter filter_manager.inclusions end
def inclusion_filter=(filter)
This overrides any inclusion filters/tags set on the command line or in
### Warning
want any inclusion filter at all.
Clears and reassigns the `inclusion_filter`. Set to `nil` if you don't
def inclusion_filter=(filter) filter_manager.include! build_metadata_hash_from([filter]) end
def initialize
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_cleaner = BacktraceCleaner.new @default_path = 'spec' @deprecation_stream = $stderr @filter_manager = FilterManager.new @preferred_options = {} @seed = srand % 0xFFFF @failure_color = :red @success_color = :green @pending_color = :yellow @default_color = :white @fixed_color = :blue @detail_color = :cyan @profile_examples = false @requires = [] @libs = [] end
def libs=(libs)
def libs=(libs) libs.map do |lib| @libs.unshift lib $LOAD_PATH.unshift lib end end
def line_numbers
def line_numbers filter.fetch(:line_numbers,[]) end
def line_numbers=(line_numbers)
def line_numbers=(line_numbers) filter_run :line_numbers => line_numbers.map{|l| l.to_i} end
def load_spec_files
- Private: -
def load_spec_files files_to_run.uniq.each {|f| load File.expand_path(f) } raise_if_rspec_1_is_loaded end
def mock_framework
def mock_framework mock_with :rspec unless @mock_framework @mock_framework end
def mock_framework=(framework)
def mock_framework=(framework) mock_with framework end
def mock_with(framework)
mod_config.custom_setting = true
config.mock_with OtherMockFrameworkAdapter do |mod_config|
it will yield the configuration object to the block e.g.
If the module responds to `configuration` and `mock_with` receives a block,
- called after verify_mocks_for_rspec (even if there are errors)
teardown_mocks_for_rspec
when expectations fail
- called after each example. Framework should raise an exception
verify_mocks_for_rspec
- called before each example
setup_mocks_for_rspec
should adhere to RSpec's mock framework adapter API:
Given a Module, includes that module in every example group. The module
any mocking framework to save a little bit of overhead.
Given `:nothing`, configures no framework. Use this if you don't use
named framework.
Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the
`framework` can be a Symbol or a Module.
Sets the mock framework adapter module.
def mock_with(framework) framework_module = case framework when Module framework when String, Symbol require case framework.to_s when /rspec/i 'rspec/core/mocking/with_rspec' when /mocha/i 'rspec/core/mocking/with_mocha' when /rr/i 'rspec/core/mocking/with_rr' when /flexmock/i '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
def order=(type)
- Api: -
def order=(type) order_and_seed_from_order(type) end
def order_and_seed_from_order(type)
def order_and_seed_from_order(type) order, seed = type.to_s.split(':') @order = order @seed = seed = seed.to_i if seed if randomize? order_groups_and_examples(&RANDOM_ORDERING) elsif order == 'default' @order, @seed = nil, nil order_groups_and_examples(&DEFAULT_ORDERING) end return order, seed end
def order_and_seed_from_seed(value)
def order_and_seed_from_seed(value) order_groups_and_examples(&RANDOM_ORDERING) @order, @seed = 'rand', value.to_i [@order, @seed] end
def order_examples(&block)
- See: #seed= -
See: #order= -
See: #order_groups_and_examples -
See: #order_groups -
def order_examples(&block) @example_ordering_block = block @order = "custom" unless built_in_orderer?(block) end
def order_groups(&block)
- See: #seed= -
See: #order= -
See: #order_groups_and_examples -
See: #order_examples -
def order_groups(&block) @group_ordering_block = block @order = "custom" unless built_in_orderer?(block) end
def order_groups_and_examples(&block)
- See: #seed= -
See: #order= -
See: #order_examples -
See: #order_groups -
def order_groups_and_examples(&block) order_groups(&block) order_examples(&block) end
def output_to_tty?(output=output_stream)
def output_to_tty?(output=output_stream) tty? || (output.respond_to?(:tty?) && output.tty?) end
def path_for(const_ref)
def path_for(const_ref) underscore_with_fix_for_non_standard_rspec_naming(const_ref) end
def profile_examples
- Api: - private
def profile_examples profile = value_for(:profile_examples, @profile_examples) if profile && !profile.is_a?(Integer) 10 else profile end end
def raise_if_rspec_1_is_loaded
def raise_if_rspec_1_is_loaded if defined?(Spec) && defined?(Spec::VERSION::MAJOR) && Spec::VERSION::MAJOR == 1 raise <<-MESSAGE 80} are running rspec-2, but it seems as though rspec-1 has been loaded as . This is likely due to a statement like this somewhere in the specs: require 'spec' se locate that statement, remove it, and try again. 80} E end end
def randomize?
def randomize? order.to_s.match(/rand/) end
def reporter
def reporter @reporter ||= begin add_formatter('progress') if formatters.empty? add_formatter(RSpec::Core::Formatters::DeprecationFormatter, deprecation_stream, output_stream) Reporter.new(*formatters) end end
def requires=(paths)
def requires=(paths) RSpec.deprecate("RSpec::Core::Configuration#requires=(paths)", :replacement => "paths.each {|path| require path}") paths.map {|path| require path} @requires += paths end
def reset
- Private: -
def reset @reporter = nil @formatters.clear end
def safe_extend(mod, host)
def safe_extend(mod, host) host.extend(mod) unless (class << host; self; end) < mod end
def safe_extend(mod, host)
def safe_extend(mod, host) host.extend(mod) unless (class << host; self; end).included_modules.include?(mod) end
def safe_include(mod, host)
- Private: -
def safe_include(mod, host) host.send(:include,mod) unless host < mod end
def seed=(seed)
- Api: -
def seed=(seed) order_and_seed_from_seed(seed) end
def set_order_and_seed(hash)
def set_order_and_seed(hash) hash[:order], seed = order_and_seed_from_order(hash[:order]) hash[:seed] = seed if seed end
def setup_load_path_and_require(paths)
- Private: -
def setup_load_path_and_require(paths) directories = ['lib', default_path].select { |p| File.directory? p } RSpec::Core::RubyProject.add_to_load_path(*directories) paths.each {|path| require path} @requires += paths end
def string_const?(str)
def string_const?(str) str.is_a?(String) && /\A[A-Z][a-zA-Z0-9_:]*\z/ =~ str end
def underscore(camel_cased_word)
def underscore(camel_cased_word) word = camel_cased_word.to_s.dup word.gsub!(/::/, '/') word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2') word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') word.tr!("-", "_") word.downcase! word end
def underscore_with_fix_for_non_standard_rspec_naming(string)
def underscore_with_fix_for_non_standard_rspec_naming(string) underscore(string).sub(%r{(^|/)r_spec($|/)}, '\\1rspec\\2') end
def value_for(key, default=nil)
def value_for(key, default=nil) @preferred_options.has_key?(key) ? @preferred_options[key] : default end
def warnings
def warnings $VERBOSE end
def warnings= value
def warnings= value $VERBOSE = !!value end