1

我正在尝试测试我的多态关联,但我似乎无法让它通过

模型:

class Foo < ApplicationRecord
  belongs_to :bar, polymorphic: true, optional: true
end

现在我的测试看起来像

RSpec.describe Foo, type: :model do
  subject { build(:foo) }
  it { is_expected.to belong_to(:bar) }
end

我得到的错误

Foo 应该属于 bar required: true (FAILED - 1)

失败:

  1. Foo 应属于 bar 要求:true 失败/错误:it { is_expected.to belongs_to(:bar) } 预期 Foo 有一个名为 bar 的 belongs_to 关联(如果 :bar 未设置,则记录验证失败;即,要么应该用 定义关联required: true,要么应该在 :bar) /# ./spec/models/foo_spec.rb:4:in `block (2 levels) in <top (required)>' 上进行存在验证

现在这个关联可以是一个 nil 值

4

1 回答 1

3

问题似乎是:

如果 :bar 未设置,则记录验证失败;

因为,你有optional: true- 这部分不满意。

看起来应该假设一个关系应该是必需的,除非你另有说明。

尝试像这样修改这个匹配器

it { is_expected.to belong_to(:bar).optional }

https://github.com/thoughtbot/should-matchers/blob/master/lib/should/matchers/active_record/association_matcher.rb#L304:L321

于 2021-09-29T16:58:50.433 回答