我正在使用 Rails 6.2、Ruby 2.7.5 和 RSpec 3.10.1。在测试关联时,我遇到了一个奇怪的错误......
Expected Voyage to have a belongs_to association called user (and for the record to fail validation if :user is unset; i.e., either the association should have been defined with `required: true`, or there should be a presence validation on :user)
我对这个错误的含义感到困惑。下面是我的模型
class Voyage < ActiveRecord::Base
…
belongs_to :user, required: true
规格是
describe Voyage, :type => :model do
describe 'associations' do
it { should belong_to :user }
codescaptain 分享的 Github 链接有对我有用的解决方案。但是,我还需要根据情况将关联设置为 required
或
optional
:
it { is_expected.to belong_to(:model).required }
it { is_expected.to belong_to(:model).optional }