首页 > 解决方案 > 使用 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

希望我已经说清楚了,还在学习

标签: ruby-on-railsrubyunit-testingrspecrspec-rails

解决方案


在规范文件中编写逻辑不是最佳实践。安装 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) }

推荐阅读