我有一个模型
class ObjectiveConcept < ActiveRecord::Base
validates :objective_id, presence: true
validates :concept_id, presence: true
validates :concept_id, uniqueness: {scope: :objective_id}
belongs_to :objective
belongs_to :concept
end
使用shoulda匹配器的模型验证为
require 'spec_helper'
describe ObjectConcept do
describe "#Validations" do
it{ should validate_presence_of(:objective_id) }
it{ should validate_presence_of(:concept_id) }
it 'should validate uniqueness of concept_id scoped to object_id' do
objective = FactoryGirl.create(:objective, name: 'some objective')
concept = FactoryGirl.create(:concept, name: 'some concept')
subject { FactoryGirl.create(:object_concept, concept_id: concept.id, objective_id: objective.id) }
should validate_uniqueness_of(:concept_id).scoped_to(:objective_id)
end
end
describe "#Associations" do
it{ should belong_to(:objective) }
it{ should belong_to(:concept) }
end
end
当我运行spec的唯一性时,我得到以下错误
ObjectiveConcept#Validations should validate uniqueness of concept_id scoped to objective_id
Failure/Error: should validate_uniqueness_of(:concept_id).scoped_to(:objective_id)
ActiveRecord::StatementInvalid:
PG::Error: ERROR: null value in column "objective_id" violates not-null constraint
DETAIL: Failing row contains (20, null, 0, 2014-09-09 10:24:36.87583, 2014-09-09 10:24:36.87583).
: INSERT INTO "objective_concepts" ("concept_id", "created_at", "objective_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"
我已根据http://rubydoc.info/github/thoughtbot/shoulda-matchers/master/Shoulda/Matchers/ActiveModel#validate_uniqueness_of-instance_method的“警告”部分中指定的唯一性验证填充主题,但无效。我该如何解决这个问题?
答案 0 :(得分:1)
通过删除主题块中的代码来修复它。
替换
subject { FactoryGirl.create(:object_concept, concept_id: concept.id, objective_id: objective.id) }
与
FactoryGirl.create(:object_concept, concept_id: concept.id, objective_id: objective.id)