There seems to be a lot of support for using let()
in rspec to initialize variables. What are some cases for using instance variables (i.e. @name
) instead?
An instance variable is a class property that can be different for each object. You create an instance variable by declaring it in the class definition, outside of any method. Instance variables are important because they allow each object to have its own copy of the data.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables.
Class variables can only be assigned when a class has been defined. Instance variables, on the other hand, can be assigned or changed at any time. Both class variables and instance variables store a value in a program, just like any other Python variable.
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
I always prefer let to an instance variable for a couple of reasons:
Instance variables come into existence when they get referenced which meant that if you make any mistake in instance variable spelling then it would definitly lead you to some issues as a new instance variable is initialized to nil. But in let you will get NameError if you misspell it.
Further you will be initializing the instance variables in before block, which means that before block will be executed every time a spec would run even if that spec dont use those instance variables you have initialized. example given below;
before do
@user = Factory :user
@movie = Factory :movie
end
it "should have user" do
@user.should eq User.first
end
it "should have movie" do
@movie.should eq Movie.first
end
Although all the specs run fine but there is not use of @movie
in first spec and no use of @user
in second.
You can also use let with bang "!" let!
, let
is lazily evaluated and will never be instantiated if you don't call it, use let
to define memoized helper , while let!
is forcefully evaluated before each method call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With