Method: RSpec::Core::Configuration#when_first_matching_example_defined

Defined in:
lib/rspec/core/configuration.rb

#when_first_matching_example_defined(*filters) ⇒ void

Defines a callback that runs after the first example with matching metadata is defined. If no examples are defined with matching metadata, it will not get called at all.

This can be used to ensure some setup is performed (such as bootstrapping a DB or loading a specific file that adds significantly to the boot time) if needed (as indicated by the presence of an example with matching metadata) but avoided otherwise.

Examples:

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


1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
# File 'lib/rspec/core/configuration.rb', line 1923

def when_first_matching_example_defined(*filters)
  specified_meta = .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.
    .delete(callback, specified_meta)

    yield
  end

  .append(callback, specified_meta)
end