質問

I am trying to make my current spec more specific to test the unique/distinct-ness of 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

I currently have nothing in for x: the spec passes and I can create and save Things from another class effectively in additional specs.

When I replace x with distinct, I get NoMethodError: undefined method 'distinct' for #<Shoulda::Matchers::....

If I replace { distinct } with { where(distinct: true) } and put conditions(distinct: true) in for x, the validation passes, but Thing class cannot be saved properly by other specs.

役に立ちましたか?

解決

No, there is no simple shoulda-matchers validation for distinct HABTM associations. distinct is just one of a large family of query mechanisms that can be utilized as part of a specifying a scope and there is no explicit support for testing it in shoulda.

You're getting the NoMethodError because distinct is not an instance method of shoulda's AssociationMatcher (see https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb for complete list).

As a related aside which you may already be aware of, distinct does not ensure uniqueness of the relation, it only ensures that you get a distinct result set when you query.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top