Module: RSpec::Core::MemoizedHelpers::ClassMethods

### Home Classes Methods

### In Files

- lib/rspec/core/memoized_helpers.rb

### Methods

- #let
- #let!
- #subject
- #subject!

### 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::MemoizedHelpers::ClassMethods

This module is extended onto {ExampleGroup}, making the methods available to be called from within example group blocks. You can think of them as being analagous to class macros.

### Public Instance Methods

let(name, &block) click to toggle source

Generates a method whose return value is memoized after the first call. Useful for reducing duplication between examples that assign values to the same local variable.

@note `let` can enhance readability when used sparingly (1,2, or

    maybe 3 declarations) in any given example group, but that can
    quickly degrade with overuse. YMMV.

@note `let` can be configured to be threadsafe or not.

    If it is threadsafe, it will take longer to access the value.
    If it is not threadsafe, it may behave in surprising ways in examples
    that spawn separate threads. Specify this on `RSpec.configure`

@note Because `let` is designed to create state that is reset between

    each example, and `before(:context)` is designed to setup state that
    is shared across _all_ examples in an example group, `let` is _not_
    intended to be used in a `before(:context)` hook.

@example

    describe Thing do
      let(:thing) { Thing.new }

      it "does something" do
        # First invocation, executes block, memoizes and returns result.
        thing.do_something

        # Second invocation, returns the memoized value.
        thing.should be_something
      end
    end

    # File lib/rspec/core/memoized_helpers.rb, line 284
    def let(name, &block)
      # We have to pass the block directly to `define_method` to
      # allow it to use method constructs like `super` and `return`.
      raise "#let or #subject called without a block" if block.nil?
      MemoizedHelpers.module_for(self).__send__(:define_method, name, &block)

      # Apply the memoization. The method has been defined in an ancestor
      # module so we can use `super` here to get the value.
      if block.arity == 1
        define_method(name) { __memoized.fetch_or_store(name) { super(RSpec.current_example, &nil) } }
      else
        define_method(name) { __memoized.fetch_or_store(name) { super(&nil) } }
      end
    end

let!(name, &block) click to toggle source

Just like `let`, except the block is invoked by an implicit `before` hook. This serves a dual purpose of setting up state and providing a memoized reference to that state.

@example

    class Thing
      def self.count
        @count ||= 0
      end

      def self.count=(val)
        @count += val
      end

      def self.reset_count
        @count = 0
      end

      def initialize
        self.class.count += 1
      end
    end

    describe Thing do
      after(:example) { Thing.reset_count }

      context "using let" do
        let(:thing) { Thing.new }

        it "is not invoked implicitly" do
          Thing.count.should eq(0)
        end

        it "can be invoked explicitly" do
          thing
          Thing.count.should eq(1)
        end
      end

      context "using let!" do
        let!(:thing) { Thing.new }

        it "is invoked implicitly" do
          Thing.count.should eq(1)
        end

        it "returns memoized version on first invocation" do
          thing
          Thing.count.should eq(1)
        end
      end
    end

    # File lib/rspec/core/memoized_helpers.rb, line 352
    def let!(name, &block)
      let(name, &block)
      before { __send__(name) }
    end

subject(name=nil, &block) click to toggle source

Declares a `subject` for an example group which can then be wrapped with `expect` using `is_expected` to make it the target of an expectation in a concise, one-line example.

Given a `name`, defines a method with that name which returns the `subject`. This lets you declare the subject once and access it implicitly in one-liners and explicitly using an intention revealing name.

When given a `name`, calling `super` in the block is not supported.

@note `subject` can be configured to be threadsafe or not.

    If it is threadsafe, it will take longer to access the value.
    If it is not threadsafe, it may behave in surprising ways in examples
    that spawn separate threads. Specify this on `RSpec.configure`

@param name [String,Symbol] used to define an accessor with an

    intention revealing name

@param block defines the value to be returned by `subject` in examples

@example

    describe CheckingAccount, "with $50" do
      subject { CheckingAccount.new(Money.new(50, :USD)) }
      it { is_expected.to have_a_balance_of(Money.new(50, :USD)) }
      it { is_expected.not_to be_overdrawn }
    end

    describe CheckingAccount, "with a non-zero starting balance" do
      subject(:account) { CheckingAccount.new(Money.new(50, :USD)) }
      it { is_expected.not_to be_overdrawn }
      it "has a balance equal to the starting balance" do
        account.balance.should eq(Money.new(50, :USD))
      end
    end

@see MemoizedHelpers#should @see MemoizedHelpers#should_not @see MemoizedHelpers#is_expected

    # File lib/rspec/core/memoized_helpers.rb, line 396
    def subject(name=nil, &block)
      if name
        let(name, &block)
        alias_method :subject, name

        self::NamedSubjectPreventSuper.__send__(:define_method, name) do
          raise NotImplementedError, "`super` in named subjects is not supported"
        end
      else
        let(:subject, &block)
      end
    end

subject!(name=nil, &block) click to toggle source

Just like `subject`, except the block is invoked by an implicit `before` hook. This serves a dual purpose of setting up state and providing a memoized reference to that state.

@example

    class Thing
      def self.count
        @count ||= 0
      end

      def self.count=(val)
        @count += val
      end

      def self.reset_count
        @count = 0
      end

      def initialize
        self.class.count += 1
      end
    end

    describe Thing do
      after(:example) { Thing.reset_count }

      context "using subject" do
        subject { Thing.new }

        it "is not invoked implicitly" do
          Thing.count.should eq(0)
        end

        it "can be invoked explicitly" do
          subject
          Thing.count.should eq(1)
        end
      end

      context "using subject!" do
        subject!(:thing) { Thing.new }

        it "is invoked implicitly" do
          Thing.count.should eq(1)
        end

        it "returns memoized version on first invocation" do
          subject
          Thing.count.should eq(1)
        end
      end
    end

    # File lib/rspec/core/memoized_helpers.rb, line 462
    def subject!(name=nil, &block)
      subject(name, &block)
      before { subject }
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.