Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is using instance variables more advantageous than using let()?

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?

like image 279
Avery Avatar asked Jan 02 '13 03:01

Avery


People also ask

Why do we use instance variables?

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.

What is the benefit of using instance variable in Java programming?

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.

How instance variables are different from class variables in Python?

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.

What is the difference between an instance variable and a class 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.


1 Answers

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.

like image 193
Muhamamd Awais Avatar answered Jan 03 '23 16:01

Muhamamd Awais