我的模型中有一个私有方法,如下所示:
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
or编写测试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