在Rails 6中,设置了belongs_to和required,但RSpec仍然抱怨我没有设置required

问题描述 投票:0回答:1

我正在使用 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 }
rspec associations ruby-on-rails-6 belongs-to
1个回答
0
投票

codescaptain 分享的 Github 链接有对我有用的解决方案。但是,我还需要根据情况将关联设置为 required

optional

it { is_expected.to belong_to(:model).required } it { is_expected.to belong_to(:model).optional }
    
© www.soinside.com 2019 - 2024. All rights reserved.