什么时候使用实例变量比使用 let() 更有利? [英] When is using instance variables more advantageous than using let()?

查看:30
本文介绍了什么时候使用实例变量比使用 let() 更有利?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有很多支持使用 let() 在 rspec 中初始化变量.使用实例变量(即 @name)代替的情况有哪些?

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?

推荐答案

出于以下几个原因,我总是更喜欢 let 而不是实例变量:

I always prefer let to an instance variable for a couple of reasons:

  • 实例变量在被引用时就存在意味着如果你在实例变量拼写中犯了任何错误,那么作为新的实例变量,它肯定会导致您遇到一些问题初始化为 nil.但是在 let 你会得到 NameError 如果你拼错了.

  • 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

尽管所有规范都运行良好,但第一个规范中没有使用 @movie,第二个规范中没有使用 @user.

Although all the specs run fine but there is not use of @movie in first spec and no use of @user in second.

你也可以使用 let 和 bang "!"let!, let 是惰性求值的,不调用永远不会被实例化,使用 let 来定义记忆化的 helper ,而 let! 在每个方法调用之前被强制求值.

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.

这篇关于什么时候使用实例变量比使用 let() 更有利?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆