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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…