1

模型

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 `block (2 levels) in '

2)RecipeIngredient 失败/错误:它 { 应该 validate_presence_of(:ingredient_id) } 当成分 ID 设置为 nil 时,没想到错误包括“不能为空”,得到错误:# ./spec/models/recipe_ingredient_spec.rb: 5:in `block (2 levels) in '

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

4

1 回答 1

-1

首先,您不需要放置on: :save子句。这是默认设置,可以关闭。

于 2013-10-02T20:05:12.937 回答