使用 RSpec 迭代某些模型属性

Iterating over certain model attributes with RSpec

我正在 Rails 和 RSpec 学习测试,我正在尝试重构一些基本单元测试。

我有一个带有 :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

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

我不确定你的模型属性是什么(你可以 post 它们吗?)但是如果你的模型有字段“蛋白质”和“卡路里”并且你验证这些是 > -1 你可能想要:

  [:protein, :calories].each do |nutr|
    subject[nutr] = -1
    expect(subject).to_not be_valid
  end

此外,如果您在模型中定义了两个不同的验证,如果您绝对想按照书上的说明进行操作,最好在两个单独的示例中对它们进行规范。

在规范文件中编写逻辑不是最佳做法。 安装 shoulda 匹配器 gem (https://github.com/thoughtbot/shoulda-matchers) 然后你可以这样写

it { is_expected.not_to allow_value(-1).for(:protein) }
it { is_expected.not_to allow_value(-1).for(:calories) }