What is the difference between using a local variable, an instance variable, and one created with the ‘let’ method inside RSpec tests?
What is the difference between using a local variable, an instance variable, and one
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using a
letis 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:Local variable
Only accessible from within one test, i.e. it cannot be reused.
Instance variable
Accessible from all tests within the example group. Assigned and evaluated on every test run in example group.
Let
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
letmay still make sense instead of a local variable if the variable logically belongs to acontextordescribeblock rather than an individual test—but that’s preference based on test structure.