你用错了这个东西,我理解你的沮丧。因此,让我给你一份在 RSpec 中使用lets 的简明手册。
使用let 的主要价值并非来自节省的处理能力。它是更广泛的 RSpec 理念的组成部分。我会试着解释一下,希望你能更容易进步......
let 很懒
当且仅当它在规范中实际使用时,您在块中定义的任何内容都会被调用:
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 已记忆
块内定义的任何事情都只会发生一次(在上下文范围内):
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 和 subject 声明不打算被调用
before(:context) 钩子,因为它们的存在是为了定义状态
在每个示例之间重置,而 before(:context) 存在于
定义在示例组中的示例之间共享的状态。
你正在做类似的事情
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