xxx
xxx

Reputation: 516

rails model test validate_uniqueness scoped

I trying to do rspec model test on validation with scope but do not understand why i have error

my model

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

my rspec test

    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

i have error

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)

I need this type of validations

Where I made a mistake?

Upvotes: 2

Views: 120

Answers (1)

Anton
Anton

Reputation: 927

Change that ports should be unique in scope of ecr

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

Upvotes: 1

Related Questions