Принадлежит спецификации, терпящей неудачу в RSpec - PullRequest
0 голосов
/ 10 января 2019

У меня есть модель с именем Option.

class Option < ApplicationRecord
  belongs_to :user
  belongs_to :company
  belongs_to :scheme
  validate :check_for_quantity

  def check_for_quantity
    if self.quantity > self.scheme.remaining_options
      errors.add(:quantity, "cannot be more than the remaining options #{ self.scheme.remaining_options.to_i}")
    end
  end
end

и модель под названием Схема.

class Scheme < ApplicationRecord
  belongs_to :share_class
  belongs_to :equity_pool
  belongs_to :company
  has_many :options, dependent: :destroy

  attr_accessor :percentage

  def ownership
    self.remaining_options * 100 / self.company.total_fdsc
  end

  def remaining_options
    self.initial_size - self.options.sum(&:quantity)
  end
end

Моя спецификация для Option Model выглядит следующим образом

require 'rails_helper'

RSpec.describe Option, type: :model do

  describe "Associations" do
    subject { create (:option) }
    it { is_expected.to belong_to(:scheme) } 
    it { is_expected.to belong_to(:vesting_schedule).optional }
    it { is_expected.to belong_to(:user) }
    it { is_expected.to belong_to(:company) }
  end
end

Когда я запускаю эту спецификацию, первый пример выдает ошибку

1) Опция Ассоциация должна принадлежать требуемой схеме: true

 Failure/Error: if self.quantity > self.scheme.remaining_options

 NoMethodError:
   undefined method `remaining_options' for nil:NilClass
 # ./app/models/option.rb:9:in `check_for_quantity'

В чем здесь проблема?

Мой заводской вариант бот

FactoryBot.define do
  factory :option do
    security "MyString"
    board_status false
    board_approval_date "2018-08-16"
    grant_date "2018-08-16"
    expiration_date "2018-08-16"
    quantity 1
    exercise_price 1.5
    vesting_start_date "2018-08-16"
    vesting_schedule nil
    scheme
    user
    company
  end
end

1 Ответ

0 голосов
/ 10 января 2019

Просто добавьте условие к проверке, чтобы оно не выполнялось, если ассоциация равна нулю.

class Option < ApplicationRecord
  belongs_to :user
  belongs_to :company
  belongs_to :scheme
  validate :check_for_quantity, unless: -> { self.scheme.nil? }

  def check_for_quantity
    if self.quantity > self.scheme.remaining_options
      errors.add(:quantity, "cannot be more than the remaining options #{ self.scheme.remaining_options.to_i}")
    end
  end
end

Вы также можете убедиться, что self.quantity - это число, а не ноль, чтобы избежать NoMethodError: undefined method > for nil:NilClass, что вы можете сделать с проверкой чисел.

class Option < ApplicationRecord
  belongs_to :user
  belongs_to :company
  belongs_to :scheme
  validates_numericality_of :quantity
  validate :check_for_quantity, if: -> { self.scheme && self.quantity }

  def check_for_quantity
    if self.quantity > self.scheme.remaining_options
      errors.add(:quantity, "cannot be more than the remaining options #{ self.scheme.remaining_options.to_i}")
    end
  end
end
...