What is the difference between using a local variable, an instance variable, and one created with the 'let' method inside RSpec tests?
Using a let
is the best choice if you need to reuse the variable, otherwise a local variable may make more sense. But you can decide for yourself given the differences:
Only accessible from within one test, i.e. it cannot be reused.
Accessible from all tests within the example group. Assigned and evaluated on every test run in example group.
Accessible from all tests within the example group. Lazily evaluated so it is only created (and the code to create it) when it is actually used in a test.
A let
may still make sense instead of a local variable if the variable logically belongs to a context
or describe
block rather than an individual test—but that's preference based on test structure.