Method: RSpec::Core::MemoizedHelpers::ClassMethods#let!

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

#let!(name, &block) ⇒ Object

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.

Examples:


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

355
356
357
358
# File 'lib/rspec/core/memoized_helpers.rb', line 355

def let!(name, &block)
  let(name, &block)
  before { __send__(name) }
end