【问题标题】:rails model test validate_uniqueness scopedrails 模型测试验证唯一性范围
【发布时间】:2023-03-07 07:11:02
【问题描述】:

我试图对范围验证进行 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)

我需要这种类型的验证

我哪里做错了?

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec


    【解决方案1】:

    更改端口在 ecr 范围内应该是唯一的

    validate :port_source, : uniqueness => { :scope => :ecr_id }
    validate :port_target, : uniqueness => { :scope => :ecr_id }
    

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多