我发现在代码中设置变量比使用 let
容易得多。 let
很挑剔,总是告诉我错误使用它的方式。
当我在规范中使用简单的变量声明时,例如
tx_good = makeTransaction1()
,一切正常。
但是当我像这样使用let
时
let(:tx_good) { makeTransaction1() }
我总是会收到一些这样的错误,告诉我它不能去这里或那里......
`let` and `subject` declarations are not intended to be called
in a `before(:context)` hook, as they exist to define state that
is reset between each example, while `before(:context)` exists to
define state that is shared across examples in an example group.
考虑到使用 let
是多么挑剔,我不得不想,是否值得我为使用它而付出额外的努力和关心。有谁知道使用 let 与仅仅预先分配一个变量相比,真正节省了多少处理时间?
我想遵循良好的测试协议(protocol),所以我希望有人能够说服我为什么我应该像(看起来)其他人一样使用 let
。
最佳答案
你错误地使用了这些东西,我理解你的沮丧。因此,让我为您提供一份在 RSpec 中使用 let
的简明手册。
使用let
的主要值(value)并非来自节省的处理能力。它是更广泛的 RSpec 理念不可或缺的一部分。我会尽力解释,希望你能更轻松地进步......
let
是懒惰的
无论您在 block 内定义什么,当且仅当它在规范中实际使用时才会被调用:
context do
let(:foo) { sleep(10000) } # will not happen
specify { expect(1).to eq(1) }
end
context do
specify do
foo = sleep(10000) # you'll wait
expect(1).to eq(1)
end
end
使用 let!
,它是 let
的急切(即非懒惰)版本
let
已被内存
block 内定义的内容只会发生一次(在上下文范围内):
context do
let(:random_number) { rand }
specify do
expect(random_number).to eq(random_number) # will always pass
end
end
如果您不需要此功能,请定义一个方法:
context do
def random_number
rand
end
specify do
expect(random_number).to eq(random_number) # sometimes pass, mostly fail
end
end
较低级别上下文中的 let
会覆盖较高级别上下文中的 let
定义:
context do
let(:x) { 1 }
specify { expect(x).to eq(1) # pass
context 'with different x' do
let(:x) { 2 }
specify { expect(x).to eq(2) # pass
end
context do
specify { expect(x).to eq(1) # pass
end
end
^ 这允许您以某种方式编写规范,其中仅在上下文中提及设置的相关“部分”,例如:
context do
let(:x) { 1 }
let(:y) { 1 }
let(:z) { 1 }
specify { expect(foo(x, y, z)).to eq(3) }
context 'when z is nil'
let(:z) { nil }
specify { expect(foo(x, y, z)).to raise_error) } # foo doesn't work with z = nil
end
context 'when x is nil'
let(:x) { nil }
specify { expect(foo(x, y, z)).to eq(15) }
end
end
奖励:subject
是一个神奇的let
# writing
subject { foo(x) }
# is almost the same as writing
let(:subject) { foo(x) }
subject
是 RSpec 中的保留概念,它是“您测试的东西”,因此您可以使用 `foo(x, y, z) 编写示例,如下所示:
context do
let(:x) { 1 }
let(:y) { 1 }
let(:z) { 1 }
subject { foo(x, y, z) }
specify { expect(subject).to eq(3) }
context 'when z is nil'
let(:z) { nil }
specify { expect(subject).to raise_error) } # foo doesn't work with z = nil
end
context 'when x is nil'
let(:x) { nil }
specify { expect(foo(subject)).to eq(15) }
end
end
关于您遇到的错误...
let
andsubject
declarations are not intended to be called in abefore(:context)
hook, as they exist to define state that is reset between each example, whilebefore(:context)
exists to
define state that is shared across examples in an example group.
你正在做类似的事情
before do
let(:x) { ... }
end
只是不要这样做,你在describe
和context
中定义let
,但你可以使用它们(不是定义它们,使用在 before
和 specify
中定义了什么):
let(:name) { 'Frank' }
before do
User.create name: name
end
specify do
expect(User.where(name: name).count).to eq(1)
end
关于rspec - "let"在 RSpec 测试中真正节省了多少时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53962748/