我尝试用范围验证进行rspec模型测试,但不明白为什么我有错误
我的模特
class EcrPortMapping < ActiveRecord::Base
belongs_to :ecr
validates :ecr_id,presence: true
validates :ecr_id, :uniqueness => {:scope => [:port_source, :port_target]}
validates :ecr_id, :uniqueness => {:scope => :port_source}
validates :ecr_id, :uniqueness => {:scope => :port_target}
end
我的rspec测试
require 'rails_helper'
RSpec.describe EcrPortMapping, type: :model do
describe 'uniqueness of ecr_id for port & target' do
it 'should validate uniqueness of ecr_id scoped to port_target & port_source' do
ecr = FactoryGirl.create(:ecr)
FactoryGirl.create(:ecr_port_mapping, ecr_id: ecr.id)
should validate_uniqueness_of(:ecr_id).scoped_to([:port_source, :port_target])
should validate_uniqueness_of(:ecr_id).scoped_to(:port_source)
should validate_uniqueness_of(:ecr_id).scoped_to(:port_target)
end
end
我有错误
Failure/Error: should validate_uniqueness_of(:ecr_id).scoped_to([:port_source, :port_target])
Did not expect errors to include "already exists" when ecr_id is set to 4,
got errors:
* "already exists" (attribute: ecr_id, value: 4) (with different value of port_source)
我需要这种类型的验证
我犯了错误?
答案 0 :(得分:1)
更改端口在ecr范围内应该是唯一的
validate :port_source, : uniqueness => { :scope => :ecr_id }
validate :port_target, : uniqueness => { :scope => :ecr_id }