モデルには、次のようなプライベートメソッドがあります。
validate :record_uniq
private
def record_uniq
if record_already_exists?
errors.add(:base, "already exists")
end
end
def record_already_exists?
question_id = measure.question_id
self.class.joins(:measure).
where(measures: {question_id: ques_id}).
where(package_id: pack_id).
exists?
end
このメソッドは、uniqueness
レコードの重複を防ぐためのスコープのようなものです。validate :record_uniq
またはを使用してテストを作成する方法を知りたいです shoulda
かrspec
?
私が試したことの例:
describe Foo do
before do
@bar = Foo.new(enr_rds_measure_id: 1, enr_rds_package_id: 2)
end
subject { @bar }
it { should validate_uniqueness_of(:record_uniq) }
end