【问题标题】:Is there a simple (should-matchers) validation for { distinct } HABTM associations?{ distinct } HABTM 关联是否有简单的(应该匹配器)验证?
【发布时间】:2013-12-31 17:10:43
【问题描述】:

我正在尝试使我当前的规范更具体,以测试 Thing.Others 的独特性/独特性

class Thing < ActiveRecord::Base
  has_and_belongs_to_many :others, -> { distinct }
end

describe Thing do
  it { should have_and_belong_to_many(:others).x }
end

我目前对 x 没有任何帮助:规范通过了,我可以在其他规范中有效地创建和保存来自另一个类的事物。

当我用distinct 替换x 时,我得到NoMethodError: undefined method 'distinct' for #&lt;Shoulda::Matchers::...。

如果我将{ distinct } 替换为{ where(distinct: true) } 并将conditions(distinct: true) 放入x,则验证通过,但其他规范无法正确保存Thing 类。

【问题讨论】:

  • 我不确定我是否完全理解第 6 行的“x”是什么。至于 NoMethodError,也许您需要定义一个自定义匹配器或包含要在您的规范中使用的匹配器spec_helper 文件?
  • 我使用 x 作为占位符,这样更容易描述我尝试过的其他规范。我对此很陌生。是否有替换不同代码段的约定?

标签: ruby-on-rails validation associations rspec-rails shoulda


【解决方案1】:

不,对于不同的 HABTM 关联没有简单的 shoulda-matchers 验证。 distinct 只是一大类查询机制之一,可用作指定范围的一部分,并且没有明确支持在 shoulda 中对其进行测试。

您获得了NoMethodError,因为distinct 不是应该的AssociationMatcher 的实例方法(请参阅https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb 以获取完整列表)。

除此之外,您可能已经知道,distinct 不确保关系的唯一性,它仅确保您在查询时获得不同的结果集。

【讨论】:

  • 感谢彼得的编辑和回答。更多谷歌搜索在你提到的一边发现了更多。可能会新年快乐。
  • 我记得,确保唯一性(即避免竞争条件)的唯一方法是创建一个 SQL 索引来保证它。如果你发现/发现了一些不同的东西,你介意让我知道吗?谢谢你,也谢谢你。
  • 你是对的。我发现的所有内容都涉及向我的索引添加唯一约束。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多