Rails:shoulda-matchersbelong_to 可选测试

mee*_*kat 9 ruby rspec ruby-on-rails shoulda rspec-rails

我有一个模型

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
Run Code Online (Sandbox Code Playgroud)

这个模型的规格看起来像这样

需要'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
Run Code Online (Sandbox Code Playgroud)

但是当我运行这个规范时,我得到了这个错误

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)>'
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会出现此错误。

Mic*_*pov 14

首先,您应该阅读对话。

@mcmire我们现在有一个预发布版本!尝试 v4.0.0.rc1 以获得可选。

然后,预期的代码应如下所示:

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
Run Code Online (Sandbox Code Playgroud)


shi*_*ovk 6

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
Run Code Online (Sandbox Code Playgroud)

Documentation