ruby - 为什么 let(:counter) { 0 } 在示例中返回 nil?
问题描述
在 Rspec 中有两个变量,它们都是整数,但在示例中(在“之前”块中),其中一个是适当的自己的值,另一个是 nil。为什么?!从未听说过这种奇怪的 rspec 行为。
尝试将 0 值更改为 1,尝试更改变量名称,尝试将“让”更改为“让!”,但行为没有改变。
代码是:
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' 之间的主要区别是什么?例如,我怎样才能得到我的计数器?
解决方案
为什么
let(:counter) { 0 }
在示例中返回 nil?
不,它没有。counter
不是你想的那样。尝试评估/打印defined?(counter)
和defined?(mocked_retry_count)
.
'counter' 和 'mocked_retry_count' 之间的主要区别是什么?
您不分配给mocked_retry_count
. 记住,let
创建方法。因此,当您尝试分配给 时counter
,您正在创建一个局部变量counter
,该变量会影响您的方法counter
(并且默认值为nil
)。
这篇文章更详细地解释了:为什么 Ruby 中的 `a = a` `nil`?
推荐阅读
- python - 更改多索引级别:“ValueError:在级别 0,代码最大值 >= 级别长度”
- angular - Primeng复选框检查问题角度
- javascript - Javascript 类变量访问
- java - 如何防止显示器永远关闭?
- c++ - 为什么从 int 到 const char* 的转换会破坏 C++
- html - 如何使用 Firefox 的开发工具检查侧边栏中的 Web 扩展内容?
- raspberry-pi - CEC 客户端未能报告电视
- python - Flask SQL Alchemy - 如何通过表单一次更新多条记录
- three.js - Orbit Controls 自动旋转一次
- django - 如何在 Django Form 中将 2 个日期时间字段分解为 1 个日期和 2 个时间?