应该在保存时保持真实存在

时间:2013-10-02 19:56:38

标签: ruby-on-rails activerecord shoulda

模型

class RecipeIngredient < ActiveRecord::Base
  validates :recipe_id, presence: true, on: :save
  validates :ingredient_id, presence: true, on: :save

  belongs_to :recipe
  belongs_to :ingredient

  has_many :quantities
 end

测试

require 'spec_helper'

describe RecipeIngredient do
  it { should validate_presence_of(:recipe_id) }
  it { should validate_presence_of(:ingredient_id) }
    it { should belong_to(:recipe) }
    it { should belong_to(:ingredient) }

    context "valid" do
      subject { RecipeIngredient.new(recipe_id: 1, ingredient_id: 1) }
      it { should be_valid }
    end
end

返回

  

故障:

     

1)RecipeIngredient        失败/错误:它{should validate_presence_of(:recipe_id)}          当recipe_id设置为nil时,没有想到错误包含“不能为空”,得到错误:        './spec/models/recipe_ingredient_spec.rb:4:in'块(2级)'

     

2)RecipeIngredient        失败/错误:它{should validate_presence_of(:ingredient_id)}          当ingredient_id设置为nil时,没有想到错误包含“不能为空”,得到错误:        './spec/models/recipe_ingredient_spec.rb:5:''块(2级)in'

我不明白为什么要添加:: save已经破坏了这个测试

1 个答案:

答案 0 :(得分:-1)

首先,您不需要放置on: :save子句。这是默认值,可以不用了。