我有一个模特
class Certificate < ApplicationRecord
notification_object
belongs_to :user
belongs_to :share_class, optional: true
belongs_to :round, optional: true
belongs_to :company, optional: true
has_many :approvals, as: :votable
end
此型号的规格如下
需要“ rails_helper”
RSpec.describe Certificate, type: :model do
it { should belong_to(:user) }
it { should belong_to(:share_class).optional }
it { should belong_to(:round).optional }
it { should belong_to(:company).optional }
it { should have_many(:approvals) }
end
但是当我运行此规范时,会出现此错误
1)证书应属于share_class可选:true
Failure/Error: it { should belong_to(:share_class).optional }
Expected Certificate to have a belongs_to association called share_class (the association should have been defined with`optional: true`, but was not)
# ./spec/models/certificate_spec.rb:5:in `block (2 levels) in <top (required)>'
我不知道为什么会收到此错误。
答案 0 :(得分:1)
class Person < ActiveRecord::Base
belongs_to :organization, optional: true
end
# RSpec
describe Person
it { should belong_to(:organization).optional }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization).optional
end
答案 1 :(得分:0)
首先,您应该阅读this对话。
@mcmire 我们现在有预发行版本!尝试使用v4.0.0.rc1获得可选。
然后,预期的代码应如下所示:
RSpec.describe Certificate, type: :model do
it { should belong_to(:user) }
it { should belong_to(:share_class).optional(true) }
it { should belong_to(:round).optional(true) }
it { should belong_to(:company).optional(true) }
it { should have_many(:approvals) }
end