ruby-on-railsrspecrspec-railsshouldashoulda-matchers

ShouldaMatchers validate_uniquess_of scoped to multiple columns


I have a model with a unique index at the db level and model validation checking for uniqueness scoped to multiple columns.

# db level
add_index :table1, %i[fk_belongs_to_id col1 col2 col3 col4], unique: true

# model level
validates :fk_belongs_to_id, uniqueness: { scope: %i[col1 col2 col3 col4], case_sensitive: false }

In the spec I have:

it { should validate_uniqueness_of(:fk_belongs_to_id).scoped_to(%i[col1 col2 col3 col4).ignoring_case_sensitivity }

But I keep getting this error:

    NoMethodError:
       undefined method `all' for Symbol:Class

How can I test for uniqueness scope with multiple columns?

I am unable to find anything that can help with this in their docs or anything. Thanks for any help!


Solution

  • You solved your own problem, which is awesome, but just a quick note of explanation for future readers:

    it { should ... } (and the alternative it { is_expected.to ... }) translate under the covers to expect(subject).to .... So, both assume that prior to that the current context has defined subject.

    The other thing to note is that, while RSpec continues to support both should and expect syntax, the general guidance is to stick with expect. In your case it doesn't matter as much since the should translates directly to expect, but in the more general usage expect solves a couple of problems with the older syntax. Check out this summary from RSpec about why.