何时使用 RSpec let()? [英] When to use RSpec let()?

查看:47
本文介绍了何时使用 RSpec let()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我倾向于使用 before 块来设置实例变量.然后我在我的例子中使用这些变量.我最近遇到了 let().根据 RSpec 文档,它用于

I tend to use before blocks to set instance variables. I then use those variables across my examples. I recently came upon let(). According to RSpec docs, it is used to

... 定义一个记忆化的辅助方法.该值将在同一示例中的多个调用中缓存,但不会跨示例缓存.

... to define a memoized helper method. The value will be cached across multiple calls in the same example but not across examples.

这与在 before 块中使用实例变量有何不同?还有什么时候应该使用 let() 还是 before()?

How is this different from using instance variables in before blocks? And also when should you use let() vs before()?

推荐答案

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

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

  • 实例变量在被引用时就会出现.这意味着,如果您对实例变量的拼写过于敏感,则会创建一个新的并将其初始化为 nil,这可能会导致细微的错误和误报.由于 let 创建了一个方法,当你拼错它时你会得到一个 NameError,我觉得这是更好的.它还可以更轻松地重构规范.
  • before(:each) 钩子将在每个示例之前运行,即使该示例不使用钩子中定义的任何实例变量.这通常不是什么大问题,但是如果实例变量的设置需要很长时间,那么您就是在浪费周期.对于let 定义的方法,初始化代码只有在示例调用它时才会运行.
  • 您可以将示例中的局部变量直接重构为 let 而无需更改示例中的引用语法.如果重构为实例变量,则必须更改您如何引用示例中的对象(例如,添加 @).
  • 这有点主观,但正如 Mike Lewis 指出的那样,我认为它使规范更易于阅读.我喜欢用 let 定义所有依赖对象并保持我的 it 块漂亮和简短的组织.
  • Instance variables spring into existence when referenced. This means that if you fat finger the spelling of the instance variable, a new one will be created and initialized to nil, which can lead to subtle bugs and false positives. Since let creates a method, you'll get a NameError when you misspell it, which I find preferable. It makes it easier to refactor specs, too.
  • A before(:each) hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let, the initialization code only runs if the example calls it.
  • You can refactor from a local variable in an example directly into a let without changing the referencing syntax in the example. If you refactor to an instance variable, you have to change how you reference the object in the example (e.g. add an @).
  • This is a bit subjective, but as Mike Lewis pointed out, I think it makes the spec easier to read. I like the organization of defining all my dependent objects with let and keeping my it block nice and short.

可以在此处找到相关链接:http://www.betterspecs.org/#let

这篇关于何时使用 RSpec let()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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