ruby-on-rails - 使用 RSpec 迭代某些模型属性
问题描述
我正在使用 RSpec 在 Rails 中学习测试,并且正在尝试重构一些基本的单元测试。
我有一个带有 :name、:protein 和 :calories 的模型。我想编写一个 .each do 循环,它只循环一些属性(:蛋白质和:卡路里),为它们设置一个负值,然后测试它们。
现在我正在编写重复的代码
it "is not valid with negative values" do
subject.calories = -1
expect(subject).to_not be_valid
end
it "is not valid with negative values" do
subject.protein = -1
expect(subject).to_not be_valid
end
由于实际上有几个属性,我希望能够写出类似的东西
nutritional_value = [:protein, :calories]
nutritional_value.each do |nutr|
subject.nutr = -1
expect(subject).to_not be_valid
end
希望我已经说清楚了,还在学习
解决方案
在规范文件中编写逻辑不是最佳实践。安装 shoulda matchers gem ( https://github.com/thoughtbot/should-matchers ) 然后你可以这样写
it { is_expected.not_to allow_value(-1).for(:protein) }
it { is_expected.not_to allow_value(-1).for(:calories) }
推荐阅读
- firebase - 在 Android 中安全地访问 Firebase 数据库
- indexing - Solr 搜索查询模式更改
- mysql - node.js mysql连接连接挂起30+秒
- google-apps-script - 当单元格值达到0时如何自动发送电子邮件并且邮件应该发送到相应的电子邮件ID
- flutter - Flutter 定义简单的 onTap 不会在嵌套类上触发
- c++ - 确定时间复杂度 C++
- oracle-cloud-infrastructure - 通过 rclone 和非经典 OCI 对象存储使用 swift 样式访问
- r - 从自定义目录安装时无法加载 R 包
- neo4j - 如何在 Neo4j 中创建具有多个关系的树结构?
- arrays - 如何打印 JSON 文件中存在的每个列表?Python