我尝试使用范围对验证唯一性进行测试,但它失败了
模型
class EcrPortMapping < ActiveRecord::Base
belongs_to :ecr
validates :ecr_id, presence: true
validates :ecr_id, uniqueness: {scope: :port_source, message: I18n.t('port_target_in_use')}
validates :ecr_id, uniqueness: {scope: :port_target, message: I18n.t('port_source_in_use')}
end
测试
RSpec.describe EcrPortMapping, type: :model do
describe 'validations' do
it 'should validate uniqueness of ecr_id scoped to port_target & port_source' do
should validate_uniqueness_of(:ecr_id).scoped_to(:port_target)
should validate_uniqueness_of(:ecr_id).scoped_to(:port_source)
end
错误
Failure/Error: should validate_uniqueness_of(:ecr_id).scoped_to(:port_target)
Expected validation to be scoped to [:port_target], but it was scoped to [:port_source].
答案 0 :(得分:0)
它失败了,因为它的作用域在:port_target
和 :port_source
上都是唯一的。您可以将多个范围传递给scoped_to
:
it 'should validate uniqueness of ecr_id scoped to port_target & port_source' do
should validate_uniqueness_of(:ecr_id).scoped_to(:port_target, :port_source)
end