When are instance variables more beneficial than using let ()?

There seems to be a lot of support for using let() in rspec to initialize variables. What are some instances of using instance variables (i.e. @name )?

+7
variables rspec
Jan 02 '13 at 3:39
source share
2 answers

I always prefer to use an instance variable for several reasons:

  • Instance variables occur when they refer to meant that if you make any mistake in the instance of the variable this will definitely lead to some problems as the new instance variable is initialized to zero. But let you get a NameError if you miss it.

  • Next, you will initialize the instance variables into a block, which means that before the block is executed every time the spec will work, even if this specification does not use these instance variables you initialized. example 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 specifications work fine, the first specification does not use @movie and does not use @user in the second.

You can also use let with bang "!" let! , let is evaluated lazily and will never be instantiated unless you name it, use let to define memoized helper, and let! is strongly evaluated before every method call.

+14
Jan 02 '13 at 7:12
source share
— -

I approve of this question, but in the end I answer the question myself.

Describe the differences first

The let method, when used, does not initialize the variable until it is specified in the test, which distinguishes it from @instance variables , which are initialized from the very beginning.

In general, there is not much uncertainty. Use @instance variables if you want to make sure the let object is initialized. But, on the other hand, it can be done the same with let! , so there is no obvious reason to use @instance variable .

In conclusion, for me there is an obvious reason to use @instance variable over let , but there is no obvious reason to use @instance variables over let!

@instance variables takes longer to load and, using them, can lead to undesirable code complexity, which could have been avoided using let or let!

You can also take a look at these two answers, perhaps this will give you additional information:

When to use RSpec let ()?

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

+7
Mar 26 '13 at 13:41
source share



All Articles