0
votes

I'm using let(:foo) { create_foo() } inside my tests. create_foo is a test helper that does some fairly time expensive setup.

So everytime a test is run, foo is created, and that takes some time. However, the foo object itself does not change, I just want to unit test methods on that object, one by one, seperated into single tests.

So, is there a RSpec equivalent of let to share the variable across multiple examples, but keep the nice things like lazy loading (if foo isn't needed) and also the automatic method definition of foo so that it can be used in shared examples, without referencing it with a @foo?

Or do I have to simply define a

def foo
  create_foo()
end
2
Since your object gets initialised once at some point in the test suite and does not change, would assigning the result of create_foo to a FOO constant in some before(:suite) configuration allow you to do what you want? - Paul Fioravanti

2 Answers

1
votes

Can you just put it in shared examples but use memoization?

def foo
  @foo ||= create_foo()
end
1
votes

Using let in this way goes against what it was designed for. You should consider using before_all which runs once per test group:

before :all do
  @instancevar = create_object()
end

Keep in mind that this may not be wise if create_object() hits a database since it may introduce coupling and maintain state between your tests.