为什么在例子中让(:counter) { 0 } returns nil?
Why let(:counter) { 0 } returns nil in example?
在Rspec中有两个变量,都是整数,但是在例子中(在'before'块中)其中一个是适当的自己的值,另一个是nil。为什么?!从未听说过这种奇怪的 rspec 行为。
尝试将 0 值更改为 1,
尝试更改变量名称,
尝试将 'let' 更改为 'let!',
但行为没有改变。
密码是:
context 'when input contains incorrect symbols' do
let(:counter) { 1 }
let(:mocked_retry_count) { 5 }
before do
allow(described_class).to receive(:gets) {
byebug
counter += 1
counter > mocked_retry_count ? 'Stop the loop' : ['$', (0..9).to_a.sample, '#', '%', '&'].sample
}
described_class.ask_kingdoms
end
end
在 byebug 的输出中我看到了
62: let(:counter) { 1 }
63: let(:mocked_retry_count) { 5 }
64: before do
65: allow(described_class).to receive(:gets) {
66: byebug
=> 67: counter += 1
68: counter > mocked_retry_count ? 'Stop the loop' : ['$', (0..9).to_a.sample, '#', '%', '&'].sample
69: }
70: described_class.ask_kingdoms
71: end
(byebug) counter
nil
(byebug) mocked_retry_count
5
'counter' 和 'mocked_retry_count' 之间的主要区别是什么?我怎样才能得到我的例子中的计数器?
Why let(:counter) { 0 }
returns nil in example?
不,不是。 counter
不是你想的那样。试试 evaluating/printing defined?(counter)
和 defined?(mocked_retry_count)
.
What is the principal difference between 'counter' and 'mocked_retry_count' ?
您没有分配给 mocked_retry_count
。请记住,let
创建方法。因此,当您尝试分配给 counter
时,您正在创建一个局部变量 counter
,它会影响您的方法 counter
(默认值为 nil
)。
这个post解释的更详细:Why is `a = a` `nil` in Ruby?
在Rspec中有两个变量,都是整数,但是在例子中(在'before'块中)其中一个是适当的自己的值,另一个是nil。为什么?!从未听说过这种奇怪的 rspec 行为。
尝试将 0 值更改为 1, 尝试更改变量名称, 尝试将 'let' 更改为 'let!', 但行为没有改变。
密码是:
context 'when input contains incorrect symbols' do
let(:counter) { 1 }
let(:mocked_retry_count) { 5 }
before do
allow(described_class).to receive(:gets) {
byebug
counter += 1
counter > mocked_retry_count ? 'Stop the loop' : ['$', (0..9).to_a.sample, '#', '%', '&'].sample
}
described_class.ask_kingdoms
end
end
在 byebug 的输出中我看到了
62: let(:counter) { 1 }
63: let(:mocked_retry_count) { 5 }
64: before do
65: allow(described_class).to receive(:gets) {
66: byebug
=> 67: counter += 1
68: counter > mocked_retry_count ? 'Stop the loop' : ['$', (0..9).to_a.sample, '#', '%', '&'].sample
69: }
70: described_class.ask_kingdoms
71: end
(byebug) counter
nil
(byebug) mocked_retry_count
5
'counter' 和 'mocked_retry_count' 之间的主要区别是什么?我怎样才能得到我的例子中的计数器?
Why
let(:counter) { 0 }
returns nil in example?
不,不是。 counter
不是你想的那样。试试 evaluating/printing defined?(counter)
和 defined?(mocked_retry_count)
.
What is the principal difference between 'counter' and 'mocked_retry_count' ?
您没有分配给 mocked_retry_count
。请记住,let
创建方法。因此,当您尝试分配给 counter
时,您正在创建一个局部变量 counter
,它会影响您的方法 counter
(默认值为 nil
)。
这个post解释的更详细:Why is `a = a` `nil` in Ruby?