9

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?

Community
  • 1
  • 1
Son of the Wai-Pan
  • 12,371
  • 16
  • 46
  • 55

2 Answers2

14

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.

Muhamamd Awais
  • 2,385
  • 14
  • 25
  • 2
    Maybe he wanted to say like this: at all points, `let` is preferable to instance variables and is always more advantageous than instance variables. – 谷口昂平 Dec 19 '14 at 04:36
8

I have favored this question, but at the end I am answering to the question myself.

First to describe the differences

The let method when used it does not initialize the variable until it is referenced in the test - which makes it different from @instance variables which are initialized from the start.

In general there is no big diffidence. Use @instance variables when you want be sure that let object is initialized. But on the other hand this can be done the same with let! , so there is no obvious reason for using @instance variable.

To conclude, to me, there is obvious reason to use @instance variable over let, but there is no obvious reason to use @instance variables over let!

@instance variables takes more time to load, and by using them, could lead to unwanted complexity in code which could be avoided by using let or let!

You can take a look at these two answers as well, maybe it will give you some more information:

When to use RSpec let()?

RSpec: What is the difference between let and a before block?

Community
  • 1
  • 1
Aleks
  • 4,866
  • 3
  • 38
  • 69