rspec-为什么let变量在it中需要@instance符号,而在expect中不需要?
对于本测试:rspec-为什么let变量在it中需要@instance符号,而在expect中不需要?,rspec,instance-variables,memoization,let,Rspec,Instance Variables,Memoization,Let,对于本测试: describe "can translate" do let(:from){592} it @from do expect(Translator.three_digits(from)).to eq 'five hundred ninety two' end end 当在it语句中使用它时,我需要将from引用为@from,但在expect测试中使用它时,我需要将其引用为from。在每种情况下,尝试使用另一种格式都会导致未知错误。为什么会有差异? 它是否反映
describe "can translate" do
let(:from){592}
it @from do
expect(Translator.three_digits(from)).to eq 'five hundred ninety two'
end
end
当在it
语句中使用它时,我需要将from
引用为@from
,但在expect
测试中使用它时,我需要将其引用为from
。在每种情况下,尝试使用另一种格式都会导致未知错误。为什么会有差异?它是否反映了我没有正确地做/理解的事情
在进一步挖掘之后,我意识到@instance变量工作不正常-它只是没有报告错误,因为@variable可以是空的。但是,如果测试失败并且输出测试文本描述,则该变量的值为空。尝试
expect{}
而不是expect()
:
或省略其描述并在一行中执行:
it { expect{Translator.three_digits(from) }.to eq 'five hundred ninety two' }
您是否希望
let(:from){592}
声明也初始化@from
实例变量?如果是这样的话,我想不会。如果没有,请详细说明为什么需要在it
块中将from
称为@from
?据我所知,您的@from
实例变量没有按预期的方式工作的原因是因为它是nil
,因为您没有在规范中的任何地方声明@from
。下面是一个小测试:
describe 'foo' do
let(:foo) { 1 }
it "@foo's value is #{@foo.inspect}" do
expect(foo).to eq(2) # deliberate fail
end
end
结果是:
1) foo @foo's value is nil # no @foo here
Failure/Error: expect(foo).to eq(2)
expected: 2
got: 1
(compared using ==)
1) foo @foo's value is 3 # it block uses @foo in describe block
Failure/Error: expect(foo).to eq(2)
expected: 2
got: 1
(compared using ==)
另一方面,我认为在规范中使用实例变量时可能会产生混淆,这在以下规范中得到了举例说明:
describe 'foo' do
let(:foo) { 1 }
before { @foo = 2 }
@foo = 3
it "@foo's value is #{@foo.inspect}" do
expect(@foo).to eq(2) # this test passes cause it uses @foo in before block
expect(foo).to eq(2) # deliberate fail
end
end
结果是:
1) foo @foo's value is nil # no @foo here
Failure/Error: expect(foo).to eq(2)
expected: 2
got: 1
(compared using ==)
1) foo @foo's value is 3 # it block uses @foo in describe block
Failure/Error: expect(foo).to eq(2)
expected: 2
got: 1
(compared using ==)