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

后端 未结 2 1369
悲哀的现实
悲哀的现实 2020-12-16 05:04

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?

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 05:27

    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.

提交回复
热议问题