Ruby on rails 错误。添加了吗?与:exclusion一起使用时返回false

Ruby on rails 错误。添加了吗?与:exclusion一起使用时返回false,ruby-on-rails,ruby,testing,rspec,rspec-rails,Ruby On Rails,Ruby,Testing,Rspec,Rspec Rails,在递归rails模型中,我验证了模型不能引用自身: validates :parent_entity, exclusion: { in: ->(entity) { [entity] } } 这是成功的,并且设置了包含正确消息的排除错误。我可以通过rails控制台对此进行批准 在Rspec测试中,我想检查是否添加了适当的排除错误: it 'parent_entity cannot be same entity as child_entity' do @child_entity1.par

在递归rails模型中,我验证了模型不能引用自身:

validates :parent_entity, exclusion: { in: ->(entity) { [entity] } }
这是成功的,并且设置了包含正确消息的排除错误。我可以通过rails控制台对此进行批准

在Rspec测试中,我想检查是否添加了适当的排除错误:

it 'parent_entity cannot be same entity as child_entity' do
  @child_entity1.parent_entity = @child_entity1
  @child_entity1.valid?
  expect(@child_entity1.errors.added?(:parent_entity, :exclusion)).to be_truthy
end
测试未能在expect中返回错误的值

前面的方法完美地适用于e。G空白错误,但不排除。如果我在测试中使用已解决的错误消息“保留”交换“:exclusion”,我可以让它工作,但这不是我想要和应该做的。

取自添加的?方法:

如果错误消息需要选项,则返回true,并显示 正确的选项,或错误的选项或缺少的选项

因此,选项必须完全匹配。
:exclusion
的必要选项是
,并作为最后一个参数传递:

@child_entity1.errors.added?(:parent_entity, :exclusion, value: @child_entity1)