Search code examples
ruby-on-railsrubyrspec

Is there a way to use Rspec let! with a scope so it can be used across multiple examples?


I'm trying to figure out a good way to handle setting rspec memoized variables that will be cleaned up after a set of tests, but not after an individual test.

I'd like it to achieve something similar to the following, but with let or something similar that doesn't require me to be responsible for reverting the state back afterwards.

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

I'd like to resolve this with a simple syntax like the following code snippet. Note: I am fully aware this results in an error. Similarly, the problem with let! and around methods is that it only provides a scope around each example.

  let(:shared_person)
  before(:all)
    shared_person
  end
  it "test 1" do
    expect(shared_person).to be_a(Person)
  end

Is there a native option, gem or library that achieves this with a simple/intuitive syntax?


Solution

  • Use the test_prof gem, let_it_be functionality.

    https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md

    Recommended by https://github.com/rspec/rspec-core/issues/3065