Class: RSpec::Core::Example

### Home Classes Methods

### In Files

- lib/rspec/core/example.rb

### Parent

Object

### Namespace

- CLASS RSpec::Core::Example::ExecutionResult
- CLASS RSpec::Core::Example::Procsy

### Methods

- ::delegate_to_metadata
- ::new
- #description
- #display_exception
- #display_exception=
- #example_group
- #fail_with_exception
- #id
- #inspect_output
- #instance_exec
- #location_rerun_argument
- #rerun_argument
- #run
- #set_aggregate_failures_exception
- #set_exception
- #skip_with_exception

### Class/Module Index

Quicksearch

- RSpec
- RSpec::Core
- RSpec::Core::AnonymousExampleGroup
- RSpec::Core::BacktraceFormatter
- RSpec::Core::Bisect
- RSpec::Core::Bisect::Coordinator
- RSpec::Core::Bisect::ExampleMinimizer
- RSpec::Core::Bisect::Runner
- RSpec::Core::Bisect::Server
- RSpec::Core::Bisect::SubsetEnumerator
- RSpec::Core::Configuration
- RSpec::Core::Configuration::DeprecationReporterBuffer
- RSpec::Core::Configuration::ExposeCurrentExample
- RSpec::Core::Configuration::MustBeConfiguredBeforeExampleGroupsError
- RSpec::Core::ConfigurationOptions
- RSpec::Core::DRbOptions
- RSpec::Core::DRbRunner
- RSpec::Core::DSL
- RSpec::Core::DSL::RSpec
- RSpec::Core::Example
- RSpec::Core::Example::ExecutionResult
- RSpec::Core::Example::Procsy
- RSpec::Core::ExampleGroup
- RSpec::Core::ExampleStatusDumper
- RSpec::Core::ExampleStatusMerger
- RSpec::Core::ExampleStatusParser
- RSpec::Core::ExampleStatusPersister
- RSpec::Core::ExclusionRules
- RSpec::Core::FilterManager
- RSpec::Core::FilterRules
- RSpec::Core::FilterableItemRepository
- RSpec::Core::FilterableItemRepository::QueryOptimized
- RSpec::Core::FilterableItemRepository::UpdateOptimized
- RSpec::Core::FlatMap
- RSpec::Core::Formatters
- RSpec::Core::Formatters::BaseFormatter
- RSpec::Core::Formatters::BaseTextFormatter
- RSpec::Core::Formatters::BisectDebugFormatter
- RSpec::Core::Formatters::BisectFormatter
- RSpec::Core::Formatters::BisectProgressFormatter
- RSpec::Core::Formatters::ConsoleCodes
- RSpec::Core::Formatters::DeprecationFormatter
- RSpec::Core::Formatters::DeprecationFormatter::DelayedPrinter
- RSpec::Core::Formatters::DeprecationFormatter::FileStream
- RSpec::Core::Formatters::DeprecationFormatter::ImmediatePrinter
- RSpec::Core::Formatters::DeprecationFormatter::RaiseErrorStream
- RSpec::Core::Formatters::DocumentationFormatter
- RSpec::Core::Formatters::ExceptionPresenter
- RSpec::Core::Formatters::ExceptionPresenter::Factory
- RSpec::Core::Formatters::ExceptionPresenter::Factory::CommonBacktraceTruncater
- RSpec::Core::Formatters::ExceptionPresenter::Factory::EmptyBacktraceFormatter
- RSpec::Core::Formatters::FallbackMessageFormatter
- RSpec::Core::Formatters::Helpers
- RSpec::Core::Formatters::HtmlFormatter
- RSpec::Core::Formatters::HtmlPrinter
- RSpec::Core::Formatters::JsonFormatter
- RSpec::Core::Formatters::Loader
- RSpec::Core::Formatters::ProfileFormatter
- RSpec::Core::Formatters::ProgressFormatter
- RSpec::Core::Formatters::Protocol
- RSpec::Core::Formatters::SnippetExtractor
- RSpec::Core::Formatters::SnippetExtractor::CoderayConverter
- RSpec::Core::Formatters::SnippetExtractor::NullConverter
- RSpec::Core::HashImitatable
- RSpec::Core::HashImitatable::ClassMethods
- RSpec::Core::Hooks
- RSpec::Core::Hooks::AfterContextHook
- RSpec::Core::Hooks::AfterHook
- RSpec::Core::Hooks::AroundHook
- RSpec::Core::Hooks::BeforeHook
- RSpec::Core::Hooks::Hook
- RSpec::Core::Hooks::HookCollections
- RSpec::Core::InclusionRules
- RSpec::Core::LegacyExampleGroupHash
- RSpec::Core::MemoizedHelpers
- RSpec::Core::MemoizedHelpers::ClassMethods
- RSpec::Core::MemoizedHelpers::ContextHookMemoized
- RSpec::Core::MemoizedHelpers::ContextHookMemoized::After
- RSpec::Core::MemoizedHelpers::ContextHookMemoized::Before
- RSpec::Core::MemoizedHelpers::NonThreadSafeMemoized
- RSpec::Core::MemoizedHelpers::ThreadsafeMemoized
- RSpec::Core::Metadata
- RSpec::Core::Metadata::ExampleGroupHash
- RSpec::Core::Metadata::ExampleHash
- RSpec::Core::Metadata::HashPopulator
- RSpec::Core::MetadataFilter
- RSpec::Core::MinitestAssertionsAdapter
- RSpec::Core::MockingAdapters
- RSpec::Core::MockingAdapters::Flexmock
- RSpec::Core::MockingAdapters::Mocha
- RSpec::Core::MockingAdapters::Null
- RSpec::Core::MockingAdapters::RR
- RSpec::Core::MockingAdapters::RSpec
- RSpec::Core::MultipleExceptionError
- RSpec::Core::MultipleExceptionError::InterfaceTag
- RSpec::Core::Mutex
- RSpec::Core::Notifications
- RSpec::Core::Notifications::CustomNotification
- RSpec::Core::Notifications::DeprecationNotification
- RSpec::Core::Notifications::ExampleNotification
- RSpec::Core::Notifications::ExamplesNotification
- RSpec::Core::Notifications::FailedExampleNotification
- RSpec::Core::Notifications::NullColorizer
- RSpec::Core::Notifications::NullNotification
- RSpec::Core::Notifications::PendingExampleFailedAsExpectedNotification
- RSpec::Core::Notifications::PendingExampleFixedNotification
- RSpec::Core::Notifications::ProfileNotification
- RSpec::Core::Notifications::SeedNotification
- RSpec::Core::Notifications::SkippedExampleNotification
- RSpec::Core::Notifications::SummaryNotification
- RSpec::Core::NullReporter
- RSpec::Core::Ordering
- RSpec::Core::Ordering::ConfigurationManager
- RSpec::Core::Ordering::Custom
- RSpec::Core::Ordering::Identity
- RSpec::Core::Ordering::Random
- RSpec::Core::Ordering::Registry
- RSpec::Core::Parser
- RSpec::Core::Pending
- RSpec::Core::Pending::PendingExampleFixedError
- RSpec::Core::Pending::SkipDeclaredInExample
- RSpec::Core::Profiler
- RSpec::Core::ProjectInitializer
- RSpec::Core::RakeTask
- RSpec::Core::ReentrantMutex
- RSpec::Core::Reporter
- RSpec::Core::RubyProject
- RSpec::Core::Runner
- RSpec::Core::Sandbox
- RSpec::Core::Set
- RSpec::Core::SharedContext
- RSpec::Core::SharedExampleGroup
- RSpec::Core::SharedExampleGroup::Registry
- RSpec::Core::SharedExampleGroup::TopLevelDSL
- RSpec::Core::SharedExampleGroupInclusionStackFrame
- RSpec::Core::SharedExampleGroupModule
- RSpec::Core::ShellEscape
- RSpec::Core::SuiteHookContext
- RSpec::Core::TestUnitAssertionsAdapter
- RSpec::Core::Time
- RSpec::Core::Version
- RSpec::Core::Warnings
- RSpec::Core::World
- RSpec::ExampleGroups
- Object

No matching classes.

# RSpec::Core::Example

Wrapper for an instance of a subclass of {ExampleGroup}. An instance of `RSpec::Core::Example` is returned by example definition methods such as {ExampleGroup.it it} and is yielded to the {ExampleGroup.it it}, {Hooks#before before}, {Hooks#after after}, {Hooks#around around}, {MemoizedHelpers::ClassMethods#let let} and {MemoizedHelpers::ClassMethods#subject subject} blocks.

This allows us to provide rich metadata about each individual example without adding tons of methods directly to the ExampleGroup that users may inadvertantly redefine.

Useful for configuring logging and/or taking some action based on the state of an example's metadata.

@example

    RSpec.configure do |config|
      config.before do |example|
        log example.description
      end

      config.after do |example|
        log example.description
      end

      config.around do |example|
        log example.description
        example.run
      end
    end

    shared_examples "auditable" do
      it "does something" do
        log "#{example.full_description}: #{auditable.inspect}"
        auditable.should do_something
      end
    end

@see ExampleGroup @note Example blocks are evaluated in the context of an instance

    of an `ExampleGroup`, not in the context of an instance of `Example`.

### Attributes

clock[RW]

@attr @private

example_group_instance[R]

@attr_reader @private

Returns the example_group_instance that provides the context for running this example.

exception[R]

@attr_reader

Returns the first exception raised in the context of running this example (nil if no exception is raised).

metadata[R]

@attr_reader

Returns the metadata object associated with this example.

reporter[R]

@return [RSpec::Core::Reporter] the current reporter for the example

### Public Class Methods

delegate_to_metadata(key) click to toggle source

@private

Used to define methods that delegate to this example's metadata.

    # File lib/rspec/core/example.rb, line 48
    def self.delegate_to_metadata(key)
      define_method(key) { @metadata[key] }
    end

new(example_group_class, description, user_metadata, example_block=nil) click to toggle source

Creates a new instance of Example. @param example_group_class [Class] the subclass of ExampleGroup in which

    this Example is declared

@param description [String] the String passed to the `it` method (or

    alias)

@param user_metadata [Hash] additional args passed to `it` to be used as

    metadata

@param example_block [Proc] the block of code that represents the

    example

@api private

    # File lib/rspec/core/example.rb, line 153
    def initialize(example_group_class, description, user_metadata, example_block=nil)
      @example_group_class = example_group_class
      @example_block       = example_block

      @metadata = Metadata::ExampleHash.create(
        @example_group_class.metadata, user_metadata,
        example_group_class.method(:next_runnable_index_for),
        description, example_block
      )

      # This should perhaps be done in `Metadata::ExampleHash.create`,
      # but the logic there has no knowledge of `RSpec.world` and we
      # want to keep it that way. It's easier to just assign it here.
      @metadata[:last_run_status] = RSpec.configuration.last_run_statuses[id]

      @example_group_instance = @exception = nil
      @clock = RSpec::Core::Time
      @reporter = RSpec::Core::NullReporter
    end

### Public Instance Methods

description() click to toggle source

Returns the string submitted to `example` or its aliases (e.g. `specify`, `it`, etc). If no string is submitted (e.g. `it { is_expected.to do_something }`) it returns the message generated by the matcher if there is one, otherwise returns a message including the location of the example.

    # File lib/rspec/core/example.rb, line 76
    def description
      description = if metadata[:description].to_s.empty?
                      location_description
                    else
                      metadata[:description]
                    end

      RSpec.configuration.format_docstrings_block.call(description)
    end

display_exception() click to toggle source

@private

The exception that will be displayed to the user -- either the failure of the example or the `pending_exception` if the example is pending.

    # File lib/rspec/core/example.rb, line 309
    def display_exception
      @exception || execution_result.pending_exception
    end

display_exception=(ex) click to toggle source

@private

Assigns the exception that will be displayed to the user -- either the failure of the example or the `pending_exception` if the example is pending.

    # File lib/rspec/core/example.rb, line 317
    def display_exception=(ex)
      if pending? && !(Pending::PendingExampleFixedError === ex)
        @exception = nil
        execution_result.pending_fixed = false
        execution_result.pending_exception = ex
      else
        @exception = ex
      end
    end

example_group() click to toggle source

Returns the example group class that provides the context for running this example.

    # File lib/rspec/core/example.rb, line 178
    def example_group
      @example_group_class
    end

fail_with_exception(reporter, exception) click to toggle source

@private

Used internally to set an exception and fail without actually executing the example when an exception is raised in before(:context).

    # File lib/rspec/core/example.rb, line 360
    def fail_with_exception(reporter, exception)
      start(reporter)
      set_exception(exception)
      finish(reporter)
    end

id() click to toggle source

@return [String] the unique id of this example. Pass

    this at the command line to re-run this exact example.

    # File lib/rspec/core/example.rb, line 117
    def id
      @id ||= Metadata.id_from(metadata)
    end

inspect_output() click to toggle source

Returns a description of the example that always includes the location.

    # File lib/rspec/core/example.rb, line 87
    def inspect_output
      inspect_output = "\"#{description}\""
      unless metadata[:description].to_s.empty?
        inspect_output << " (#{location})"
      end
      inspect_output
    end

instance_exec(*args, &block) click to toggle source

@private

    # File lib/rspec/core/example.rb, line 377
    def instance_exec(*args, &block)
      @example_group_instance.instance_exec(*args, &block)
    end

location_rerun_argument() click to toggle source

Returns the location-based argument that can be passed to the `rspec` command to rerun this example.

    # File lib/rspec/core/example.rb, line 96
    def location_rerun_argument
      @location_rerun_argument ||= begin
        loaded_spec_files = RSpec.configuration.loaded_spec_files

        Metadata.ascending(metadata) do |meta|
          return meta[:location] if loaded_spec_files.include?(meta[:absolute_file_path])
        end
      end
    end

rerun_argument() click to toggle source

Returns the location-based argument that can be passed to the `rspec` command to rerun this example.

@deprecated Use {location_rerun_argument} instead. @note If there are multiple examples identified by this location, they will use {id}

    to rerun instead, but this method will still return the location (that's why it is deprecated!).

    # File lib/rspec/core/example.rb, line 111
    def rerun_argument
      location_rerun_argument
    end

run(example_group_instance, reporter) click to toggle source

@api private instance_execs the block passed to the constructor in the context of the instance of {ExampleGroup}. @param example_group_instance the instance of an ExampleGroup subclass

    # File lib/rspec/core/example.rb, line 189
    def run(example_group_instance, reporter)
      @example_group_instance = example_group_instance
      @reporter = reporter
      hooks.register_global_singleton_context_hooks(self, RSpec.configuration.hooks)
      RSpec.configuration.configure_example(self)
      RSpec.current_example = self

      start(reporter)
      Pending.mark_pending!(self, pending) if pending?

      begin
        if skipped?
          Pending.mark_pending! self, skip
        elsif !RSpec.configuration.dry_run?
          with_around_and_singleton_context_hooks do
            begin
              run_before_example
              @example_group_instance.instance_exec(self, &@example_block)

              if pending?
                Pending.mark_fixed! self

                raise Pending::PendingExampleFixedError,
                      'Expected example to fail since it is pending, but it passed.',
                      [location]
              end
            rescue Pending::SkipDeclaredInExample
              # no-op, required metadata has already been set by the `skip`
              # method.
            rescue Exception => e
              set_exception(e)
            ensure
              run_after_example
            end
          end
        end
      rescue Exception => e
        set_exception(e)
      ensure
        @example_group_instance = nil # if you love something... let it go
      end

      finish(reporter)
    ensure
      RSpec.current_example = nil
    end

set_aggregate_failures_exception(exception) click to toggle source

@private

Used to set the exception when `aggregate_failures` fails.

    # File lib/rspec/core/example.rb, line 346
    def set_aggregate_failures_exception(exception)
      return set_exception(exception) unless display_exception

      exception = RSpec::Core::MultipleExceptionError::InterfaceTag.for(exception)
      exception.add display_exception
      self.display_exception = exception
    end

set_exception(exception) click to toggle source

@private

Used internally to set an exception in an after hook, which captures the exception but doesn't raise it.

    # File lib/rspec/core/example.rb, line 333
    def set_exception(exception)
      return self.display_exception = exception unless display_exception

      unless RSpec::Core::MultipleExceptionError === display_exception
        self.display_exception = RSpec::Core::MultipleExceptionError.new(display_exception)
      end

      display_exception.add exception
    end

skip_with_exception(reporter, exception) click to toggle source

@private

Used internally to skip without actually executing the example when skip is used in before(:context).

    # File lib/rspec/core/example.rb, line 370
    def skip_with_exception(reporter, exception)
      start(reporter)
      Pending.mark_skipped! self, exception.argument
      finish(reporter)
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.