Ruby on rails 如何在rails中测试rspec shoulda以进行自定义验证?
我的模型中有一个私有方法,如下所示:Ruby on rails 如何在rails中测试rspec shoulda以进行自定义验证?,ruby-on-rails,ruby-on-rails-3,rspec,rspec-rails,shoulda,Ruby On Rails,Ruby On Rails 3,Rspec,Rspec Rails,Shoulda,我的模型中有一个私有方法,如下所示: 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(:me
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
这种方法更像是一种防止重复记录的唯一性
作用域。我想知道如何使用shoulda
或rspec
为validate:record\u uniq
编写测试
我尝试的示例:
简单-构建一个未通过验证的对象,对其进行验证,并验证是否设置了正确的错误消息 例如(如果您有一个名为City的模型):
下面是我将使用rspec3语法所做的
it 'validates that city is unique' do
city = City.new('already taken name')
expect(city).to be_invalid
expect(city.errors[:base]).to include('already exists')
end
如果您能更清楚地理解任何示例,我会更感激。我更新了问题,并使用了您的答案,但得到了一个
错误,预期错误为1:base,得到0
,那么您的测试就完成了。现在让它通过。有点混乱。。。我会试试的。谢谢如果您想更改城市。应该有(1)。error\u on(:base)到使用新的expect
语法,请这样做:expect(city)。to have(1)。error\u on(:base)
可以使用expect(city.errors.full\u messages)。to/not\u到include('full message')
it 'validates that city is unique' do
city = City.new # add in stuff to make sure it will trip your validation
city.valid?
city.should have(1).error_on(:base) # or
city.errors(:base).should eq ["already exists"]
end
it 'validates that city is unique' do
city = City.new('already taken name')
expect(city).to be_invalid
expect(city.errors[:base]).to include('already exists')
end