rspec/rspec-core

add :context scope to let method

SamuelFrost opened this issue · 2 comments

let! / let with :context scope so it can be used across multiple examples

I'd like a reliable way to be able to set values with memoized access and state control across multiple examples by passing a scope to the let method.

Desired behavior

The following should not create a new person in test2. And should use the person created on the first call of shared_person. (Please excuse the use of non-core specifics)

RSpec.describe Person do
  let(:shared_person, :context) { create(:person) }
  it "test 1" do
    expect(shared_person).to be_a(Person)
  end

  it "test 2" do
    expect(shared_person).to be_a(Person)
  end
end

Currently something like this would achieve similar results, but requires the developer to be responsible for data cleanup and such.

RSpec.describe Person do
  before(:context) do
    @shared_value = create(:person)
  end

  after(:context) do
    @shared_value.destroy
  end

  it "test 1" do
    expect(@shared_value).to be_a(Person)
  end

  it "test 2" do
    expect(@shared_value).to be_a(Person)
  end
end

pirj commented

I can highly recommend let_it_be from test-prof.
But since it’s mostly used to save on heavy lifting, specifically Rails and factories, we have no intention of implementing this in rspec-core.

I concur with @pirj here, this isn't something I'd want to bring into rspec-core because it brings more shared state into the test class as opposed to the example [the instance].