类: RSpec::Core::Configuration

继承
Object
  • Object
显示全部
包含
Module.new, Hooks
定义于
lib/rspec/core/configuration.rb

概述

存储运行时配置信息。

配置选项从多个文件加载,并与命令行开关和 SPEC_OPTS 环境变量合并。

优先级顺序(后续条目会覆盖先前条目中的冲突)

  • 全局 ($XDG_CONFIG_HOME/rspec/options,如果不存在则为 ~/.rspec)
  • 特定于项目 (./.rspec)
  • 本地 (./.rspec-local)
  • 命令行选项
  • SPEC_OPTS

例如,在本地文件中设置的选项将覆盖全局文件中设置的选项。

可以使用 --options 命令行参数,用单独的自定义文件覆盖全局文件、特定于项目的文件和本地文件。

示例

标准设置

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

钩子

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

另请参见

实例属性摘要 折叠

实例方法摘要 折叠

构造函数详细信息

#initialize配置

构建一个对象来存储运行时配置选项并设置默认值

528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/rspec/core/configuration.rb', line 528
def initialize
  # rubocop:disable Style/GlobalVars
  @start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now
  # rubocop:enable Style/GlobalVars
  @expectation_frameworks = []
  @include_modules = FilterableItemRepository::QueryOptimized.new(:any?)
  @extend_modules  = FilterableItemRepository::QueryOptimized.new(:any?)
  @prepend_modules = FilterableItemRepository::QueryOptimized.new(:any?)
  @bisect_runner = RSpec::Support::RubyFeatures.fork_supported? ? :fork : :shell
  @bisect_runner_class = nil
  @before_suite_hooks = []
  @after_suite_hooks  = []
  @mock_framework = nil
  @files_or_directories_to_run = []
  @loaded_spec_files = Set.new
  @color = false
  @color_mode = :automatic
  @pattern = '**{,/*/**}/*_spec.rb'
  @exclude_pattern = ''
  @failure_exit_code = 1
  @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(:any?)
  @threadsafe = true
  @max_displayed_failure_line_count = 10
  @full_cause_backtrace = false
  @world = World::Null
  @shared_context_metadata_behavior = :trigger_inclusion
  @pending_failure_output = :full
  define_built_in_hooks
end

实例属性详细信息

#bisect_runner符号

注意

此选项仅在您通过 --require 加载的文件中设置时,才会被 --bisect 使用。

确定在二分查找期间使用哪个二分查找运行程序实现来运行套件的子集。您的选择是

  • :shell:通过执行 shell 命令执行规范运行,每次启动 RSpec 和您的应用程序环境。此运行程序是兼容性最广的运行程序,但速度不快。在不支持分叉的平台上,这是默认值。
  • :fork:在父进程中预先启动 RSpec 和您的应用程序环境,然后为每个规范运行分叉一个子进程。此运行程序通常比 :shell 运行程序快得多,但在某些情况下无法使用。在支持分叉的平台上,这是默认值。如果您使用此运行程序,您应该确保所有的一次性设置逻辑都放在 before(:suite) 钩子中,而不是在由 --require 加载的文件的顶层运行。

返回值

  • (符号)
499
500
501
# File 'lib/rspec/core/configuration.rb', line 499
def bisect_runner
  @bisect_runner
end

#color布尔值

已弃用。

不再推荐,因为行为复杂。相反,请依赖于 TTY 默认情况下会显示颜色的事实,或者将 #color_mode 设置为 :on 以在非 TTY 输出上显示颜色。

如果输出是 TTY,则启用彩色输出。从 RSpec 3.6 开始,这是默认行为,保留此选项仅用于向后兼容性。

返回值

  • (布尔值)

另请参见

922
923
924
# File 'lib/rspec/core/configuration.rb', line 922
def color
  value_for(:color) { @color }
end

#color_mode布尔值

确定是否以彩色显示输出的模式。其中之一

  • :automatic - 如果输出是 TTY,则输出将以彩色显示(默认值)
  • :on - 输出将以彩色显示,无论输出是否为 TTY
  • :off - 输出将不会以彩色显示

返回值

  • (布尔值)

另请参见

935
936
937
# File 'lib/rspec/core/configuration.rb', line 935
def color_mode
  value_for(:color_mode) { @color_mode }
end

#default_color符号

默认输出颜色。默认为 :white,但可以设置为以下之一:[:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

返回值

  • (符号)
358
# File 'lib/rspec/core/configuration.rb', line 358
add_setting :default_color

#default_path字符串

注意

间接调用 rspec 的其他脚本将忽略此设置。

如果未向 rspec 命令提供路径,则要使用的路径(默认值:"spec")。允许您只键入 rspec 而不是 rspec spec 来运行 spec 目录中的所有示例。

返回值

  • (字符串)
120
# File 'lib/rspec/core/configuration.rb', line 120
add_read_only_setting :default_path

#detail_color符号

用于打印详细信息的颜色。默认为 :cyan,但可以设置为以下之一:[:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

返回值

  • (符号)
372
# File 'lib/rspec/core/configuration.rb', line 372
add_setting :detail_color

#drb布尔值

通过 DRb 运行示例(默认值:false)。RSpec 不提供 DRb 服务器,但您可以使用 spork 之类的工具。

返回值

  • (布尔值)
130
# File 'lib/rspec/core/configuration.rb', line 130
add_setting :drb

#drb_portvoid

drb_port(默认值:nil)。

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

#dry_runvoid

打印套件的格式化程序输出,而不运行任何示例或钩子。

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

#error_exit_code整数

如果示例之外存在任何错误,则要返回的退出代码(默认值:failure_exit_code)

返回值

  • (整数)
248
# File 'lib/rspec/core/configuration.rb', line 248
add_setting :error_exit_code

#error_streamvoid

默认值:$stderr

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

#example_status_persistence_file_pathString #example_status_persistence_file_path=(value) ⇒ void

用于持久保存示例状态的文件路径。对于 --only-failures--next-failure CLI 选项来说是必需的。

重载

  • #example_status_persistence_file_path字符串

    返回文件路径。

    返回值

    • (String)

      文件路径

  • #example_status_persistence_file_path=(value) ⇒void

    参数

    • value (String)

      文件路径

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

#exclude_pattern字符串

排除与该模式匹配的文件。

返回值

  • (字符串)
300
# File 'lib/rspec/core/configuration.rb', line 300
define_reader :exclude_pattern

#fail_fastvoid

如果指定,则指示在清理和退出之前所需的失败次数(默认值:nil)。也可以是 true,以便在第一次失败时失败并退出

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

#fail_if_no_examples布尔值

当没有 RSpec 示例时是否失败(默认值:false)。

返回值

  • (布尔值)
253
# File 'lib/rspec/core/configuration.rb', line 253
add_setting :fail_if_no_examples

#failure_color符号

用于指示失败的颜色。默认为 :red,但可以设置为以下之一:[:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

返回值

  • (符号)
351
# File 'lib/rspec/core/configuration.rb', line 351
add_setting :failure_color

#failure_exit_code整数

如果存在任何失败,则要返回的退出代码(默认值:1)。

返回值

  • (整数)
243
# File 'lib/rspec/core/configuration.rb', line 243
add_setting :failure_exit_code

#files_to_run数组

RSpec 将运行的规范文件。

返回值

  • (Array)

    要运行的指定文件

1096
1097
1098
# File 'lib/rspec/core/configuration.rb', line 1096
def files_to_run
  @files_to_run ||= get_files_to_run(@files_or_directories_to_run)
end

#fixed_color符号

当挂起的示例被修复时使用的颜色。默认为 :blue,但可以设置为以下之一:[:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

返回值

  • (符号)
365
# File 'lib/rspec/core/configuration.rb', line 365
add_setting :fixed_color

#libsArray<String>

返回由 -I 命令行选项添加到加载路径的目录。

返回值

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

#max_displayed_failure_line_countvoid

在失败报告中显示的失败源代码行的最大数量(默认为 10)。返回 [整数]

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

#only_failuresvoid (只读) 也称为:only_failures?

指示是否正在使用 --only-failures(或 --next-failure)标志。

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

#output_streamIO, 字符串

确定 RSpec 将其输出发送到的位置。默认值:$stdout

返回值

  • (IO, 字符串)
270
# File 'lib/rspec/core/configuration.rb', line 270
define_reader :output_stream

#pattern字符串

加载与该模式匹配的文件(默认值:'**{,/*/**}/*_spec.rb')。

返回值

  • (字符串)
289
# File 'lib/rspec/core/configuration.rb', line 289
define_reader :pattern

#pending_color符号

用于打印挂起示例的颜色。默认为 :yellow,但可以设置为以下之一:[:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

返回值

  • (符号)
344
# File 'lib/rspec/core/configuration.rb', line 344
add_setting :pending_color

#pending_failure_outputvoid

格式化挂起示例的输出。可以设置为

  • :full(默认值) - 挂起示例看起来类似于失败
  • :no_backtrace - 与上述相同,但没有回溯
  • :skip - 不显示该部分 return [Symbol]

引发

  • (ArgumentError)
472
# File 'lib/rspec/core/configuration.rb', line 472
add_read_only_setting :pending_failure_output

#profile_examplesvoid

此方法是私有 API 的一部分。如果可能,您应该避免使用此方法,因为它可能会在将来被删除或更改。

@profile_examplestrue 时,将 profile_examples 默认为 10 个示例。

322
# File 'lib/rspec/core/configuration.rb', line 322
attr_writer :profile_examples

#project_source_dirsArray<String>

指定包含项目源代码的目录。发生错误时,RSpec 会浏览回溯以查找要打印的源代码行。它首先查找来自项目源目录之一的行,以便例如,它打印期望值或断言调用,而不是期望值或断言框架的源代码。

返回值

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

#requiresArray<String>

指示配置为要求的文件。

返回值

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

#run_all_when_everything_filteredvoid

已弃用。

使用 #filter_run_when_matching 代替,用于您想要忽略的特定过滤器(如果都不匹配)。

如果没有任何匹配配置的过滤器,则运行所有示例(默认值:false)。

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

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

配置 RSpec 如何处理作为共享示例组定义的一部分传递的元数据。例如,给定此共享示例组定义

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

...RSpec 有两种方法可以处理 :db => true 元数据,每种方法都有一个对应的配置选项

  1. :trigger_inclusion:此共享上下文将被隐式包含在任何具有 :db => true 元数据的组(或示例)中。
  2. :apply_to_host_groups:元数据将被所有宿主组和示例的元数据哈希继承。

:trigger_inclusion 是 RSpec 3.5 之前的遗留行为,但应被视为已弃用。相反,您可以使用 include_context 显式包含一个组

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

...或者您可以配置 RSpec,使其使用与配置模块包含相似的 API,根据匹配的元数据来包含上下文

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

:apply_to_host_groups 是 RSpec 3.5 的一项新功能,并将是 RSpec 4 中唯一支持的行为。

重载

  • #shared_context_metadata_behavior:trigger_inclusion, :apply_to_host_groups

    返回配置的行为。

    返回值

    • (:trigger_inclusion, :apply_to_host_groups)

      配置的行为

  • #shared_context_metadata_behavior=(value) ⇒void

    参数

    • value (:trigger_inclusion, :apply_to_host_groups)

      设置配置的行为

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

#silence_filter_announcementsvoid

不要打印过滤器信息,例如“运行选项:包含 :focus=>true”(默认值 false)。返回 [布尔值]

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

#success_color符号

用于指示成功的颜色。默认为 :green,但可以设置为以下之一:[:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]

返回值

  • (符号)
337
# File 'lib/rspec/core/configuration.rb', line 337
add_setting :success_color

#threadsafevoid

在可用时使用线程安全选项。目前,这将对 let 块等已记忆值放置一个互斥锁。返回 [布尔值]

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

实例方法详细信息

#add_formatter(formatter) ⇒ void #add_formatter(formatter, output) ⇒ void 也称为:formatter=

将格式化程序添加到 RSpec 将在此运行中使用的一组中。

参数

  • formatter (Class, String, Object)

    要使用的格式化程序。可以是 CLI 支持的任何字符串值(p/progressd/doc/documentationh/htmlj/json),任何实现格式化程序协议并已向 RSpec 注册为格式化程序的类,或格式化程序实例。

  • output (String, IO) (默认值: output_wrapper)

    格式化程序将写入其输出的位置。可以是 IO 对象或指向文件的字符串路径。如果没有提供,将使用配置的 output_stream(默认情况下为 $stdout)。

另请参见

996
997
998
# File 'lib/rspec/core/configuration.rb', line 996
def add_formatter(formatter, output=output_wrapper)
  formatter_loader.add(formatter, output)
end

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

向 RSpec.configuration 对象添加自定义设置。

RSpec.configuration.add_setting :foo

在内部使用,并由扩展框架(如 rspec-rails)使用,以便它们可以添加特定于域的配置设置。例如

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

add_setting 在配置对象上创建三个方法,一个 setter,一个 getter 和一个谓词

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

参数

  • opts (Hash) (默认值: {})

    一组可自定义的选项

选项哈希(opts):

  • :default (Symbol)

    为生成的 getter 和谓词方法设置默认值

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

    使用 :alias_with 将 setter、getter 和谓词别名到另一个名称或多个名称

    add_setting(:foo, :alias_with => :bar)
    add_setting(:foo, :alias_with => [:bar, :baz])
    
659
660
661
662
663
664
665
# File 'lib/rspec/core/configuration.rb', line 659
def add_setting(name, opts={})
  default = opts.delete(:default)
  (class << self; self; end).class_exec do
    add_setting(name, opts)
  end
  __send__("#{name}=", default) if default
end

#after(scope = nil, *meta, &block) ⇒void 也称为:prepend_after

定义 after 钩子。有关完整文档,请参阅 Hooks#after

此方法与 Hooks#after 仅在一个方面有所不同:它支持 :suite 范围。具有 :suite 范围的钩子将在整个套件的最后一个示例执行后运行一次。与 :suite 一起传递的条件实际上会被忽略。

2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
# File 'lib/rspec/core/configuration.rb', line 2029
def after(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @after_suite_hooks.unshift Hooks::AfterHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.after(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

#alias_example_group_to(new_name, *args) ⇒void

注意

如果 expose_dsl_globally 设置为 true,则定义的别名也将添加到顶层(例如 main 和模块中)。

创建一个方法,该方法使用提供的元数据定义一个示例组。可用于定义示例组/元数据快捷方式。

示例

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

另请参见

1209
1210
1211
1212
# File 'lib/rspec/core/configuration.rb', line 1209
def alias_example_group_to(new_name, *args)
  extra_options = Metadata.build_hash_from(args)
  RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options)
end

#alias_example_to(name, *args) ⇒void

注意

以下特定示例别名 (pending) 已为您定义。

注意

谨慎使用。这扩展了规范中使用的语言,但没有添加任何其他文档。我们在 RSpec 中使用它来定义方法,例如 focusxit,但我们也为这些方法添加了文档。

创建一个方法,该方法委派给 example,包括提交的 args。在内部使用,用于添加 example 的变体,如 pending

示例

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

参数

  • name (String)

    示例名称别名

  • args (Array<Symbol>, Hash)

    生成的示例的元数据

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

#alias_it_behaves_like_to(new_name, report_label = '') ⇒void 也称为:alias_it_should_behave_like_to

注意

谨慎使用。这扩展了规范中使用的语言,但没有添加任何其他文档。我们在 RSpec 中使用它来定义 it_should_behave_like(为了向后兼容),但我们也为该方法添加了文档。

为 it_should_behave_like 定义一个别名,该别名允许在包含共享示例时使用不同的语言(如“it_has_behavior”或“it_behaves_like”)。

示例

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

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

block 添加到同一范围(:example:context:suite)中的 after 块列表的末尾,与 #after 相反,后者将钩子添加到列表的开头。

有关完整的 after 钩子文档,请参阅 Hooks#after

此方法与 Hooks#append_after 仅在一个方面有所不同:它支持 :suite 范围。具有 :suite 范围的钩子将在整个套件的最后一个示例执行后运行一次。与 :suite 一起传递的条件实际上会被忽略。

2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
# File 'lib/rspec/core/configuration.rb', line 2059
def append_after(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @after_suite_hooks << Hooks::AfterHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.append_after(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

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

block 注册为 around 钩子。

有关完整的 around 钩子文档,请参阅 Hooks#around

2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
# File 'lib/rspec/core/configuration.rb', line 2077
def around(scope=nil, *meta, &block)
  # defeat Ruby 2.5 lazy proc allocation to ensure
  # the methods below are passed the same proc instances
  # so `Hook` equality is preserved. For more info, see:
  # https://bugs.ruby-lang.org/issues/14045#note-5
  block.__id__
  add_hook_to_existing_matching_groups(meta, scope) { |g| g.around(scope, *meta, &block) }
  super(scope, *meta, &block)
end

#backtrace_exclusion_patternsArray<Regexp>

用于从堆栈跟踪中排除行的正则表达式。

默认情况下,排除来自 ruby(和 jruby)源代码、已安装的 gem、任何“bin”目录中的任何内容以及任何 RSpec 库(在 gem 安装之外)的代码行。

您可以通过 getter 修改列表,或通过 setter 替换列表。

要覆盖此行为并显示完整的堆栈跟踪,请在命令行、.rspec 文件中或 RSpec rake 任务的 rspec_options 属性中使用 --backtrace

返回值

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

#backtrace_exclusion_patterns=(patterns) ⇒void

设置用于在堆栈跟踪中排除行的正则表达式。

参数

  • patterns (Array<Regexp>)

    设置 backtrace_formatter exclusion_patterns

703
704
705
# File 'lib/rspec/core/configuration.rb', line 703
def backtrace_exclusion_patterns=(patterns)
  @backtrace_formatter.exclusion_patterns = patterns
end

#backtrace_inclusion_patternsArray<Regexp>

用于在堆栈跟踪中包含行的正则表达式。

默认值为 [Regexp.new Dir.getwd]。

与排除模式和包含模式匹配的代码行将被包含。

您可以通过 getter 修改列表,或通过 setter 替换列表。

返回值

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

#backtrace_inclusion_patterns=(patterns) ⇒void

设置用于在堆栈跟踪中包含行的正则表达式。

722
723
724
# File 'lib/rspec/core/configuration.rb', line 722
def backtrace_inclusion_patterns=(patterns)
  @backtrace_formatter.inclusion_patterns = patterns
end

#before(scope = nil, *meta, &block) ⇒void 也称为:append_before

定义 before 钩子。有关完整文档,请参阅 Hooks#before

此方法与 Hooks#before 仅在一个方面有所不同:它支持 :suite 范围。具有 :suite 范围的钩子将在整个套件的第一个示例执行前运行一次。与 :suite 一起传递的条件实际上会被忽略。

1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
# File 'lib/rspec/core/configuration.rb', line 1974
def before(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @before_suite_hooks << Hooks::BeforeHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.before(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

#color_enabled?(output = output_stream) ⇒布尔值

检查是否为特定输出启用了颜色。

参数

  • output (IO) (默认值: output_stream)

    要使用的输出流,默认为当前 output_stream

返回值

  • (布尔值)
943
944
945
946
947
948
949
950
# File 'lib/rspec/core/configuration.rb', line 943
def color_enabled?(output=output_stream)
  case color_mode
  when :on then true
  when :off then false
  else # automatic
    output_to_tty?(output) || (color && tty?)
  end
end

#default_formattervoid

如果没有设置格式化程序,将使用的格式化程序。默认为“progress”。

1003
1004
1005
# File 'lib/rspec/core/configuration.rb', line 1003
def default_formatter
  formatter_loader.default_formatter
end

#default_formatter=(value) ⇒void

设置如果未设置其他格式化程序,要使用的回退格式化程序。

示例


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

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

定义一个回调,该回调可以分配派生的元数据值。

示例

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

参数

  • filters (Array<Symbol>, Hash)

    元数据过滤器,确定将触发回调的哪些示例或组元数据哈希。如果没有给出任何值,则回调将针对所有组和示例的元数据哈希运行。

传递的参数

  • metadata (Hash)

    来自示例或组的原始元数据哈希。根据需要在此块中进行修改。

1898
1899
1900
1901
# File 'lib/rspec/core/configuration.rb', line 1898
def (*filters, &block)
  meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  @derived_metadata_blocks.append(block, meta)
end

#deprecation_streamIO, 字符串

确定在何处打印弃用警告。默认为 $stderr

返回值

  • (IO, String)

    要写入的 IO 或文件名

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

#deprecation_stream=(value) ⇒void

确定在何处打印弃用警告。

参数

  • value (IO, String)

    要写入的 IO 或文件名

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

#disable_monkey_patching!void

注意

仅当用户正在使用这些框架(无论是显式使用还是通过未将 mock_withexpect_with 设置为其他任何值而隐式使用)时,才会配置 rspec-mocks 和 rspec-expectations。

注意

如果用户将此选项与 mock_with :mocha(或类似内容)一起使用,他们仍然会在 mocha 的测试环境中拥有有效的猴子补丁。

为 RSpec 启用零猴子补丁模式。它会删除顶级 DSL 方法(describeshared_examples_for 等)对 mainModule 的猴子补丁,而是要求您在这些方法前面加上 RSpec.。它为 rspec-mocks 和 rspec-expectations 启用了仅期望语法。它只是禁用对用户正在使用的 RSpec 部分的猴子补丁。

示例


# It disables all monkey patching.
RSpec.configure do |config|
  config.disable_monkey_patching!
end
# Is an equivalent to
RSpec.configure do |config|
  config.expose_dsl_globally = false
  config.mock_with :rspec do |mocks|
    mocks.syntax = :expect
    mocks.patch_marshal_to_support_partial_doubles = false
  end
  config.expect_with :rspec do |expectations|
    expectations.syntax = :expect
  end
end
1871
1872
1873
1874
1875
1876
# File 'lib/rspec/core/configuration.rb', line 1871
def disable_monkey_patching!
  self.expose_dsl_globally = false
  self.disable_monkey_patching = true
  conditionally_disable_mocks_monkey_patching
  conditionally_disable_expectations_monkey_patching
end

#exclusion_filtervoid

返回 exclusion_filter。如果没有设置,则返回一个空哈希。

1369
1370
1371
# File 'lib/rspec/core/configuration.rb', line 1369
def exclusion_filter
  filter_manager.exclusions
end

#exclusion_filter=(filter) ⇒void

清除并重新分配 exclusion_filter。如果您根本不希望任何排除过滤器,请将其设置为 nil

警告

这将覆盖命令行或配置文件中设置的任何排除过滤器/标签。

1362
1363
1364
1365
# File 'lib/rspec/core/configuration.rb', line 1362
def exclusion_filter=(filter)
  meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
  filter_manager.exclude_only meta
end

#expect_with(*frameworks) ⇒void

设置要包含在每个示例组中的期望框架模块。

frameworks 可以是 :rspec:test_unit:minitest、自定义模块,或这些模块的任何组合

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

RSpec 将将 :rspec:minitest:test_unit 转换为相应的模块。

配置

如果模块响应 configurationexpect_with 将在给定块的情况下传递 configuration 对象

config.expect_with OtherExpectationFramework do |custom_config|
  custom_config.custom_setting = true
end
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
# File 'lib/rspec/core/configuration.rb', line 858
def expect_with(*frameworks)
  modules = frameworks.map do |framework|
    case framework
    when Module
      framework
    when :rspec
      require 'rspec/expectations'
      # Tag this exception class so our exception formatting logic knows
      # that it satisfies the `MultipleExceptionError` interface.
      ::RSpec::Expectations::MultipleExpectationsNotMetError.__send__(
        :include, MultipleExceptionError::InterfaceTag
      )
      ::RSpec::Matchers
    when :test_unit
      require 'rspec/core/test_unit_assertions_adapter'
      ::RSpec::Core::TestUnitAssertionsAdapter
    when :minitest
      require 'rspec/core/minitest_assertions_adapter'
      ::RSpec::Core::MinitestAssertionsAdapter
    else
      raise ArgumentError, "#{framework.inspect} is not supported"
    end
  end
  if (modules - @expectation_frameworks).any?
    assert_no_example_groups_defined(:expect_with)
  end
  if block_given?
    raise "expect_with only accepts a block with a single argument. " \
          "Call expect_with #{modules.length} times, " \
          "once with each argument, instead." if modules.length > 1
    raise "#{modules.first} must respond to `configuration` so that " \
          "expect_with can yield it." unless modules.first.respond_to?(:configuration)
    yield modules.first.configuration
  end
  @expectation_frameworks.push(*modules)
end

#expectation_framework=(framework) ⇒void

委派给 expect_with(framework)。

831
832
833
# File 'lib/rspec/core/configuration.rb', line 831
def expectation_framework=(framework)
  expect_with(framework)
end

#expectation_frameworksvoid

返回配置的期望框架适配器模块。

819
820
821
822
823
824
825
826
827
828
# File 'lib/rspec/core/configuration.rb', line 819
def expectation_frameworks
  if @expectation_frameworks.empty?
    begin
      expect_with :rspec
    rescue LoadError
      expect_with Module.new
    end
  end
  @expectation_frameworks
end

#expose_current_running_example_as(method_name) ⇒void

通过命名的辅助方法公开当前正在运行的示例。RSpec 2.x 通过 example 公开了这一点,但在 RSpec 3.0 中,示例改为通过传递给 itbeforelet 等等的参数来公开。但是,一些扩展 gem(例如 Capybara)依赖于 RSpec 2.x 的 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.[:type] == "foo"
  end
end

参数

  • method_name (Symbol)

    辅助方法的名称

1809
1810
1811
1812
1813
1814
1815
1816
# File 'lib/rspec/core/configuration.rb', line 1809
def expose_current_running_example_as(method_name)
  ExposeCurrentExample.module_exec do
    extend RSpec::SharedContext
    let(method_name) { |ex| ex }
  end
  include ExposeCurrentExample
end

#expose_dsl_globally=(value) ⇒void

使用此选项通过 Modulemain 对象公开核心 RSpec DSL。它将自动设置,但您可以覆盖它以删除 DSL。默认值:true

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

#expose_dsl_globally?布尔值

指示 DSL 是否已从模块和 main 中公开。默认值:true

返回值

  • (布尔值)
143
144
145
# File 'lib/rspec/core/configuration.rb', line 143
def expose_dsl_globally?
  Core::DSL.exposed_globally?
end

#extend(mod, *filters) ⇒void

告诉 RSpec 使用 mod 扩展示例组。在 mod 中定义的方法会公开给示例组(而不是示例)。使用 filters 来约束要扩展的组。

类似于 include,但行为被添加到示例组(这些组是类),而不是示例(这些示例是这些类的实例)。

示例


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

另请参见

1518
1519
1520
1521
1522
# File 'lib/rspec/core/configuration.rb', line 1518
def extend(mod, *filters)
  define_mixed_in_module(mod, filters, @extend_modules, :extend) do |group|
    safe_extend(mod, group)
  end
end

#filter_gems_from_backtrace(*gem_names) ⇒void

注意

此添加的模式将匹配其常见位置的命名宝石(例如系统宝石、捆绑器提供的宝石、作为捆绑器的 :git 依赖项安装的宝石等),但不保证对所有可能的宝石位置都适用。例如,如果您在具有完全无关名称的目录中拥有宝石源,并使用捆绑器的 :path 选项,则不会筛选它。

添加 #backtrace_exclusion_patterns,它将从回溯中过滤掉命名宝石的行。

示例

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

参数

  • gem_names (Array<String>)

    要过滤的宝石名称

742
743
744
745
746
# File 'lib/rspec/core/configuration.rb', line 742
def filter_gems_from_backtrace(*gem_names)
  gem_names.each do |name|
    @backtrace_formatter.filter_gem(name)
  end
end

#filter_run_excluding(*args) ⇒void

exclusion_filter 添加键值对。如果 args 包含任何不属于哈希的符号,则每个符号都将被视为哈希中的键,其值为 true

注意

使用此方法设置的过滤器可以从命令行或配置文件(例如 .rspec)覆盖。

示例

# 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
1349
1350
1351
1352
1353
# File 'lib/rspec/core/configuration.rb', line 1349
def filter_run_excluding(*args)
  meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
  filter_manager.exclude_with_low_priority meta
  static_config_filter_manager.exclude_with_low_priority Metadata.deep_hash_dup(meta)
end

#filter_run_including(*args) ⇒void 也称为: filter_run

inclusion_filter 添加键值对。如果 args 包含任何不属于哈希的符号,则每个符号都将被视为哈希中的键,其值为 true

注意

使用此方法设置的过滤器可以从命令行或配置文件(例如 .rspec)覆盖。

示例

# 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
1275
1276
1277
1278
1279
# File 'lib/rspec/core/configuration.rb', line 1275
def filter_run_including(*args)
  meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering)
  filter_manager.include_with_low_priority meta
  static_config_filter_manager.include_with_low_priority Metadata.deep_hash_dup(meta)
end

#filter_run_when_matching(*args) ⇒void

仅当任何示例匹配时才应用提供的过滤器,与 #filter_run 相反,后者始终应用,即使没有示例匹配,在这种情况下也不会运行任何示例。这允许您保留仅用于临时使用的配置过滤器。最常见的示例是焦点过滤:config.filter_run_when_matching :focus。这样配置后,您可以通过使用 :focus 元数据标记示例或分组来临时聚焦示例或分组,或者在前面加上 f(如 fdescribefcontextfit),因为它们是 describe/context/it 的别名,带有 :focus 元数据。

1291
1292
1293
1294
1295
# File 'lib/rspec/core/configuration.rb', line 1291
def filter_run_when_matching(*args)
  when_first_matching_example_defined(*args) do
    filter_run(*args)
  end
end

#format_docstrings(&block) ⇒void

使用提供的块格式化文档字符串输出。

示例

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

#formatters数组

返回当前在 FormatterLoader 中加载的格式化程序的副本,用于自省。

注意,由于这是一个副本,任何修改都将被忽略。

返回值

  • (Array)

    当前加载的格式化程序

1024
1025
1026
# File 'lib/rspec/core/configuration.rb', line 1024
def formatters
  formatter_loader.formatters.dup
end

#full_backtrace=(true_or_false) ⇒void

切换完整回溯。

908
909
910
# File 'lib/rspec/core/configuration.rb', line 908
def full_backtrace=(true_or_false)
  @backtrace_formatter.full_backtrace = true_or_false
end

#full_backtrace?布尔值

检查是否启用了完整回溯。

返回值

  • (Boolean)

    是否启用了完整回溯

902
903
904
# File 'lib/rspec/core/configuration.rb', line 902
def full_backtrace?
  @backtrace_formatter.full_backtrace?
end

#full_description数组

返回完整描述过滤器。

返回值

  • (Array)

    完整描述过滤器

977
978
979
# File 'lib/rspec/core/configuration.rb', line 977
def full_description
  filter.fetch :full_description, nil
end

#full_description=(description) ⇒void

运行匹配所有要运行的文件中 description 的示例。

参数

  • description (String, Regexp)

    要过滤的模式

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

#include(mod, *filters) ⇒void

注意

过滤的模块包含也可以应用于具有匹配元数据的单个示例。就像 Ruby 的对象模型是每个对象都拥有一个只有一个实例的单例类一样,RSpec 的模型是每个示例都拥有一个只包含一个示例的单例示例组。

告诉 RSpec 将 mod 包含在示例组中。在 mod 中定义的方法暴露给示例(而不是示例组)。使用 filters 来限制包含模块的组或示例。

示例


module AuthenticationHelpers
  def (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, | [:request, :controller].include?(type) })
end
describe "edit profile", :preferences, :type => :request do
  it "can be viewed by owning user" do
     preferences(users(:jdoe), :lang => 'es')
    get "/profiles/jdoe"
    assert_select ".username", :text => 'jdoe'
  end
end

另请参见

1428
1429
1430
1431
1432
# File 'lib/rspec/core/configuration.rb', line 1428
def include(mod, *filters)
  define_mixed_in_module(mod, filters, @include_modules, :include) do |group|
    safe_include(mod, group)
  end
end

#include_context(shared_group_name, *filters) ⇒void

注意

过滤的上下文包含也可以应用于具有匹配元数据的单个示例。就像 Ruby 的对象模型是每个对象都拥有一个只有一个实例的单例类一样,RSpec 的模型是每个示例都拥有一个只包含一个示例的单例示例组。

告诉 RSpec 将命名共享示例组包含在示例组中。使用 filters 来限制包含示例组的组或示例。

示例


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
     admin_user
    get "/admin"
    expect(response).to be_ok
  end
  it "cannot be viewed by guests" do
     guest_user
    get "/admin"
    expect(response).to be_forbidden
  end
end

另请参见

1475
1476
1477
1478
# File 'lib/rspec/core/configuration.rb', line 1475
def include_context(shared_group_name, *filters)
  shared_module = world.shared_example_group_registry.find([:main], shared_group_name)
  include shared_module, *filters
end

#inclusion_filtervoid 也称为: filter

返回 inclusion_filter。如果尚未设置,则返回一个空哈希。

1313
1314
1315
# File 'lib/rspec/core/configuration.rb', line 1313
def inclusion_filter
  filter_manager.inclusions
end

#inclusion_filter=(filter) ⇒void 也称为: filter=

清除并重新分配 inclusion_filter。如果根本不希望任何包含过滤器,则设置为 nil

警告

这将覆盖在命令行或配置文件中设置的任何包含过滤器/标签。

1304
1305
1306
1307
# File 'lib/rspec/core/configuration.rb', line 1304
def inclusion_filter=(filter)
  meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering)
  filter_manager.include_only meta
end

#mock_framework符号

返回配置的模拟框架适配器模块。

返回值

  • (符号)
669
670
671
672
673
674
675
676
677
678
# File 'lib/rspec/core/configuration.rb', line 669
def mock_framework
  if @mock_framework.nil?
    begin
      mock_with :rspec
    rescue LoadError
      mock_with :nothing
    end
  end
  @mock_framework
end

#mock_framework=(framework) ⇒void

委托给 mock_framework=(framework)。

681
682
683
# File 'lib/rspec/core/configuration.rb', line 681
def mock_framework=(framework)
  mock_with framework
end

#mock_with(framework) ⇒void

设置模拟框架适配器模块。

framework 可以是 Symbol 或 Module。

对于 :rspec:mocha:flexmock:rr 中的任何一个,都会配置命名框架。

对于 :nothing,则不配置任何框架。如果您不使用任何模拟框架,请使用此方法来节省一些开销。

对于 Module,则在每个示例组中包含该模块。该模块应遵循 RSpec 的模拟框架适配器 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)

如果该模块响应 configuration,并且 mock_with 接收一个块,则它将把配置对象传递给该块,例如

config.mock_with OtherMockFrameworkAdapter do |mod_config|
  mod_config.custom_setting = true
end
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/rspec/core/configuration.rb', line 786
def mock_with(framework)
  framework_module =
    if framework.is_a?(Module)
      framework
    else
      const_name = MOCKING_ADAPTERS.fetch(framework) do
        raise ArgumentError,
              "Unknown mocking framework: #{framework.inspect}. " \
              "Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}"
      end
      RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}"
      RSpec::Core::MockingAdapters.const_get(const_name)
    end
  new_name, old_name = [framework_module, @mock_framework].map do |mod|
    mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed
  end
  unless new_name == old_name
    assert_no_example_groups_defined(:mock_framework)
  end
  if block_given?
    raise "#{framework_module} must respond to `configuration` so that " \
          "mock_with can yield it." unless framework_module.respond_to?(:configuration)
    yield framework_module.configuration
  end
  @mock_framework = framework_module
end

#on_example_group_definition(&block) ⇒void

在定义示例组之前调用块

2112
2113
2114
# File 'lib/rspec/core/configuration.rb', line 2112
def on_example_group_definition(&block)
  on_example_group_definition_callbacks << block
end

#on_example_group_definition_callbacksvoid

此方法是私有 API 的一部分。如果可能,您应该避免使用此方法,因为它可能会在将来被删除或更改。

返回一个块数组,在定义示例组之前调用这些块

2118
2119
2120
# File 'lib/rspec/core/configuration.rb', line 2118
def on_example_group_definition_callbacks
  @on_example_group_definition_callbacks ||= []
end

#order=(value) ⇒void

设置默认的全局排序策略。默认情况下,这可以是 :defined:random 之一,但可以通过 register_ordering API 自定义。如果 order 设置为 'rand:<seed>',则还会设置 seed。

另请参见

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

#prepend(mod, *filters) ⇒void

告诉 RSpec 使用 mod 向示例组添加前缀。在 mod 中定义的方法暴露给示例(而不是示例组)。使用 filters 来限制要向其添加前缀的模块的组。

类似于 include,但模块在示例组的类之前包含在祖先链中。

示例


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

另请参见

1557
1558
1559
1560
1561
# File 'lib/rspec/core/configuration.rb', line 1557
def prepend(mod, *filters)
  define_mixed_in_module(mod, filters, @prepend_modules, :prepend) do |group|
    safe_prepend(mod, group)
  end
end

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

block 添加到同一范围(:example:context:suite)中的 before 块列表的开头,与 #before 相反,后者将钩子添加到列表的末尾。

有关完整的 before 钩子文档,请参见 Hooks#before

此方法与 Hooks#prepend_before 只有一点不同:它支持 :suite 范围。具有 :suite 范围的钩子将在整个套件的第一个示例执行之前运行一次。与 :suite 一起传递的条件实际上会被忽略。

2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
# File 'lib/rspec/core/configuration.rb', line 2004
def prepend_before(scope=nil, *meta, &block)
  handle_suite_hook(scope, meta) do
    @before_suite_hooks.unshift Hooks::BeforeHook.new(block, {})
  end || begin
    # defeat Ruby 2.5 lazy proc allocation to ensure
    # the methods below are passed the same proc instances
    # so `Hook` equality is preserved. For more info, see:
    # https://bugs.ruby-lang.org/issues/14045#note-5
    block.__id__
    add_hook_to_existing_matching_groups(meta, scope) { |g| g.prepend_before(scope, *meta, &block) }
    super(scope, *meta, &block)
  end
end

#raise_errors_for_deprecations!void

将弃用警告转换为错误,以便显示调用点的完整回溯。当您需要更多上下文来解决弃用问题(而不是通常提供的单行调用点)时,这很有用。

示例


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

#raise_on_warning=(value) ⇒void

将 RSpec 警告转换为错误。当您希望 RSpec 在“严格”无警告的情况下运行时,这很有用。(注意,这不会捕获或引发 Ruby 警告)。

示例


RSpec.configure do |rspec|
  rspec.raise_on_warning = true
end
1779
1780
1781
1782
1783
1784
1785
# File 'lib/rspec/core/configuration.rb', line 1779
def raise_on_warning=(value)
  if value
    RSpec::Support.warning_notifier = RAISE_ERROR_WARNING_NOTIFIER
  else
    RSpec::Support.warning_notifier = RSpec::Support::DEFAULT_WARNING_NOTIFIER
  end
end

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

注意

传递符号 :global 来设置将用于对顶层示例组以及没有声明 :order 元数据的任何示例组进行排序的排序策略。

注册一个命名排序策略,该策略稍后可用于通过向示例组添加 :order => <name> 元数据来对示例组的子组进行排序。

示例

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

参数

  • name (Symbol)

    排序的名称。

产量

  • 将对给定示例或示例组进行排序的块

传递的参数

产量返回

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

#reporterRSpec::Core::Reporter

返回当前配置的报告器。

返回值

1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/rspec/core/configuration.rb', line 1056
def reporter
  # @reporter_buffer should only ever be set in this method to cover
  # initialization of @reporter.
  @reporter_buffer || @reporter ||=
    begin
      @reporter_buffer = DeprecationReporterBuffer.new
      formatter_loader.prepare_default output_wrapper, deprecation_stream
      @reporter_buffer.play_onto(formatter_loader.reporter)
      @reporter_buffer = nil
      formatter_loader.reporter
    end
end

#seedvoid

随机排序的种子(默认值:每次运行时随机生成)。

当您使用 --order random 运行规范时,RSpec 会为随机化生成一个随机种子,并将其打印到 output_stream(假设您使用的是 RSpec 的内置格式化程序)。如果您发现排序依赖项(即示例会根据顺序间歇性地失败),请设置此项(在 Configuration 或在命令行上使用 --seed),以便在调试问题时使用相同的种子运行。

实际上,我们建议您使用命令行方法,这样您就不会意外地将种子编码起来。

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

#seed=(value) ⇒void

设置种子值,并将默认的全局排序设置为随机。

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

#treat_symbols_as_metadata_keys_with_true_values=(_value) ⇒void

已弃用。

此配置选项是在 RSpec 2 中添加的,为在 RSpec 3 中将此行为设置为默认行为铺平了道路。现在,此选项是一个无操作选项。

383
384
385
386
387
388
389
390
# File 'lib/rspec/core/configuration.rb', line 383
def (_value)
  RSpec.deprecate(
    "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=",
    :message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " \
                "is deprecated, it is now set to true as default and " \
                "setting it to false has no effect."
  )
end

#warnings=(value) ⇒void

打开或关闭 Ruby 警告。

1758
1759
1760
# File 'lib/rspec/core/configuration.rb', line 1758
def warnings=(value)
  $VERBOSE = !!value
end

#warnings?布尔值

返回是否启用了 Ruby 警告。

返回值

  • (Boolean)

    是否启用了 Ruby 警告。

1763
1764
1765
# File 'lib/rspec/core/configuration.rb', line 1763
def warnings?
  $VERBOSE
end

#when_first_matching_example_defined(*filters) ⇒void

定义一个回调,该回调在定义了第一个具有匹配元数据的示例之后运行。如果未定义任何具有匹配元数据的示例,则根本不会调用它。

这可以用来确保如果需要(如具有匹配元数据的示例的存在所指示)执行一些设置(例如启动数据库或加载特定文件,这会大大增加启动时间),否则避免执行这些设置。

示例

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
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
# File 'lib/rspec/core/configuration.rb', line 1921
def when_first_matching_example_defined(*filters)
  specified_meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering)
  callback = lambda do |example_or_group_meta|
    # Example groups do not have `:example_group` metadata
    # (instead they have `:parent_example_group` metadata).
    return unless example_or_group_meta.key?(:example_group)
    # Ensure the callback only fires once.
    @derived_metadata_blocks.delete(callback, specified_meta)
    yield
  end
  @derived_metadata_blocks.append(callback, specified_meta)
end