Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

rspec - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...