Rails - RSpec - “让"和“让"之间的区别和“让!" [英] Rails - RSpec - Difference between "let" and "let!"

查看:20
本文介绍了Rails - RSpec - “让"和“让"之间的区别和“让!"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了 RSpec 手册 说的是区别,但有些事情仍然令人困惑.所有其他来源,包括The RSpec Book"只解释了let",而Rails 3 Way"和手册一样令人困惑.

I have read what the RSpec manual says about the difference, but some things are still confusing. Every other source, including "The RSpec Book" only explain about "let", and "The Rails 3 Way" is just as confusing as the manual.

我知道let"仅在调用时进行评估,并在范围内保持相同的值.所以在 manual 第一个测试通过,因为let"只被调用一次,第二个测试通过,因为它增加了第一个测试的值(在第一个测试中评估了一次,值为 1).

I understand that "let" is only evaluated when invoked, and keeps the same value within a scope. So it makes sense that in the first example in the manual the first test passes as the "let" is invoked only once, and the second test passes as it adds to the value of the first test (which was evaluated once in the first test and has the value of 1).

接下来,因为让!"定义时评估,再次调用时,测试是否应该不会失败,因为count.should eq(1)"应该改为count.should eq(2)"?

Following that, since "let!" evaluates when defined, and again when invoked, should the test not fail as "count.should eq(1)" should have instead be "count.should eq(2)"?

任何帮助将不胜感激.

推荐答案

它不是在定义时调用,而是在每个示例之前调用(然后它被记住并且不会被示例再次调用).这样,count 的值为 1.

It's not invoked when defined, but rather before each example (and then it's memoized and not invoked again by the example). This way, count will have a value of 1.

无论如何,如果您有另一个示例,则再次调用 before 钩子 - 以下所有测试均通过:

Anyway, if you have another example, the before hook is invoked again - all of the following tests pass:

$count = 0
describe "let!" do
  invocation_order = []

  let!(:count) do
    invocation_order << :let!
    $count += 1
  end

  it "calls the helper method in a before hook" do
    invocation_order << :example
    invocation_order.should == [:let!, :example]
    count.should eq(1)
  end

  it "calls the helper method again" do
    count.should eq(2)
  end
end

这篇关于Rails - RSpec - “让"和“让"之间的区别和“让!"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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