MZa*_*oza 3 rspec ruby-on-rails shoulda-matchers
我正在尝试测试我的多态关联,但我似乎无法让它通过
模型:
class Foo < ApplicationRecord
belongs_to :bar, polymorphic: true, optional: true
end
Run Code Online (Sandbox Code Playgroud)
现在我的测试看起来像
RSpec.describe Foo, type: :model do
subject { build(:foo) }
it { is_expected.to belong_to(:bar) }
end
Run Code Online (Sandbox Code Playgroud)
我收到的错误
Foo
is expected to belong to bar required: true (FAILED - 1)
Failures:
> 1) Foo is expected to belong to bar required: true
> Failure/Error: it { is_expected.to belong_to(:bar) }
> Expected Foo to have a belongs_to association called bar (and for the record to fail validation if :bar is unset; i.e., either the
> association should have been defined with `required: true`, or there
> should be a presence validation on :bar)
> /# ./spec/models/foo_spec.rb:4:in `block (2 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)
现在这个关联可以是零值
问题似乎是:
如果 :bar 未设置,则记录验证失败;
因为,你有optional: true——这部分不满意。
看起来应该假设应该需要一个关系,除非你另有说明。
尝试像这样修改这个匹配器
it { is_expected.to belong_to(:bar).optional }
Run Code Online (Sandbox Code Playgroud)