【发布时间】:2019-01-10 17:10:24
【问题描述】:
我有一个名为 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) 选项关联应该属于所需的方案: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
【问题讨论】:
-
你用的是FactoryBot,我猜?您是否将方案关联添加到选项工厂?该错误表示测试对象没有方案
-
是的,我确实添加了方案关联
-
我试过了,还是一样的错误
-
我刚开始学习 rspec 和测试,我正在尝试测试我的框架。然后这发生了。我知道这没关系,但现在我发现了一个问题,我不能把它留在那里对吗?
-
这个测试失败的原因一定是有什么意义的,应该有解决方案吧?
标签: ruby-on-rails ruby rspec-rails shoulda