属于 RSpec 失败的规范

Belong to spec failing in RSpec

我有一个名为 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

和一个名为 Scheme 的模型。

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

我的期权模型规范如下所示

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) Option Associations 预计属于要求的方案: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

只需在验证中添加一个条件,以便在关联为零时不会触发验证。

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 是一个数字而不是 nil 以避免 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