使用should匹配器测试唯一性范围验证



我有一个模型

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

使用should匹配器的模型验证是

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

当我运行唯一性规范时,我得到以下错误

 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"

我已经按照"Caveat"部分的规定填写了唯一性验证的主题http://rubydoc.info/github/thoughtbot/shoulda-matchers/master/Shoulda/Matchers/ActiveModel#validate_uniqueness_of-instance_method,但没有效果。我该如何解决这个问题?

通过从主题块中删除代码来修复它。

更换

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)

最新更新