mercredi 11 octobre 2017

Custom validator on associated model make other Rspec model tests break

I have 2 models sharing a simple belong_to/has_many relation: Room belongs to Building

I created a custom validator called total_number_rooms_limited_to_15 that ensures I can't create more than 15 rooms for a given Building.

class Room < ActiveRecord::Base

    # -- Relationships --------------------------------------------------------
  belongs_to :admin_user,     :foreign_key => 'admin_user_id'
  belongs_to :building,        :foreign_key => 'building_id'

  # -- Validations ----------------------------------------------------------              

  validates :room_filename,
              presence: true             

  # associated models primary key validates 
  validates :admin_user_id,
     presence: true
  validates :building_id,
     presence: true  

  validate :total_number_rooms_limited_to_15

  private

    def total_number_rooms_limited_to_15
      errors[:base] <<  "There can't be more than 15 rooms. There are already 15 .
                        <br/>Please remove another one or drop trying adding this one.".html_safe unless ( self.building.rooms.count < 15 )
    end

But the problem is that after creating this new validator, all my "usual" basic tests fail.

require 'spec_helper'

RSpec.describe Room, type: :model do

  before(:each) do
    @attr = {
      room_filename:                               "xyz" 
    }
  end  

  # -- Models Tests --------------------------------------------------------
  describe "tests on ST's models validations for room_filename" do
    it { is_expected.to validate_presence_of(:room_filename) }    
    it { is_expected.not_to allow_value(" ").for(:room_filename) }    
  end

All give me the following error message:

1) Room tests on ST's models validations for room_filename should validate that :room_filename cannot be empty/falsy
     Failure/Error:
       errors[:base] <<  "There can't be more than 15 rooms. There are already 15 .
                         <br/>Please remove another one or drop trying adding this one.".html_safe unless ( self.rooms.count < 15 )

     NoMethodError:
       undefined method `rooms' for nil:NilClass

I tried adding inside @attr the attribute a associated "virtual" building but it not work out;, getting the same error message:

before(:each) do
    @attr = {
      room_filename:                               "xyz",
      building_id:                                 1
    }

Aucun commentaire:

Enregistrer un commentaire