ruby-on-rails - 如何在 Rspec 中为哈希创建模拟
问题描述
我是日本人。对不起,英语很丑。
我想创建哈希模拟。
所以,我试试这段代码,
但发生错误
To allow expectations on `nil` and suppress this message, set `RSpec::Mocks.configuration.allow_message_expectations_on_nil` to `true`. To disallow expectations on `nil`, set `RSpec::Mocks.configuration.allow_message_expectations_on_nil` to `false`.
有没有别的写法?请教我。
AppointmentRank.new(
id: appointment.id,
name: @rank[appointment.rank_id]
)
@rank
是哈希。
rspec
let(:rank){{ 1 => 'S', 2 => 'A', 3 => 'B' }}
let(:rank_id){2}
allow(@rank).to receive(:[]).with(rank_id).and_return('A')
解决方案
问题是它let
不会创建实例变量。
您的let
行创建了名为并且在您的测试中可用的方法:rank
rank_id
RSpec.describe "let behavior" do
let(:rank){{ 1 => 'S', 2 => 'A', 3 => 'B' }}
let(:rank_id){2}
it "defines a method not an instance variable" do
expect(@rank).to be_nil
expect(rank).to be_a Hash
end
end
所以换句话说,除非你定义它们,否则不要在你的测试中使用@rank
or 。@rank_id
使用rank
andrank_id
代替
Ruby 中的实例变量如果未声明,则为 nil。这就是为什么它不会引发错误 call @rank
,即使它实际上是未定义的。
推荐阅读
- git - 从 git diff 日志中删除索引
- distcc - 使用 distcc 运行构建时如何检查列出的所有服务器是否实际正在使用
- vba - 如何在 Powerdesigner 中访问扩展集合的子记录?
- azure-pipelines - azure data factory v2 从数据湖中摄取具有不同文件名和结构的文件
- css - 难以在应用模板中自定义 body bgcolor;尝试将应用程序名称移动到 INSTALLED APPS 的 django 管理应用程序上,覆盖引导程序
- flutter - 在服务器上上传多张图片无法正常工作
- mongodb - 如何将 Kubernetes 配置映射和密码设置为 mongodb 环境变量
- python - 如何从用户输入运行 cmd 命令,然后提示输入第二个输入?
- swift - 导航栏:“隐藏”标题,但为后续的后退按钮保留它
- python - Python Flask socketIO 服务器未运行