gpt4 book ai didi

ruby - rpsec的 "let"是如何使用memoization的?

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:05 24 4
gpt4 key购买 nike

它在“RSpec Core 3.5”中说:

Use let to define a memoized helper method

我觉得他们的例子不是很清楚。他们是说 :count 的表达式只对一个规范求值一次,然后在每个规范之间再次求值吗?

我特别感兴趣的是了解使用 let 的记忆化如何与 ActiveRecord 对象一起工作。

最佳答案

Are they saying that the expression for :count is only evaluated once for a spec, and again between every spec?

来自 docs 的回答:

The value will be cached across multiple calls in the same example but not across examples.

所以是的,它会为每个示例评估一次。

换句话说,每个 it block 都会计算一次该值。

我发现他们的示例非常有表现力,看:

$count = 0
RSpec.describe "let" do
let(:count) { $count += 1 }

# count will not change no matter how many times we reference it in this it block
it "memoizes the value" do
expect(count).to eq(1) # evaluated (set to 1)
expect(count).to eq(1) # did not change (still 1)
end

# count will be set to 2 and remain 2 untill the end of the block
it "is not cached across examples" do
expect(count).to eq(2) # evaluated in new it block
end
end

我们在 memoizes the value 示例中引用了 count 两次,但它只被评估了一次。

关于ruby - rpsec的 "let"是如何使用memoization的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com