[英]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.我有一个 model 在数据库级别具有唯一索引,并且 model 验证检查范围为多列的唯一性。
# 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?如何使用多列测试 scope 的唯一性?
I am unable to find anything that can help with this in their docs or anything.我无法在他们的文档或任何内容中找到任何可以帮助解决此问题的内容。 Thanks for any help!
谢谢你的帮助!
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...
. it { should... }
(以及it { is_expected.to... }
的替代方法)在幕后翻译为expect(subject).to...
。 So, both assume that prior to that the current context has defined subject
.因此,两者都假设在此之前当前上下文已经定义了
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
.需要注意的另一件事是,虽然 RSpec 继续支持
should
和expect
语法,但一般指导是坚持使用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.在您的情况下,这并不重要,因为
should
直接转换为expect
,但在更一般的用法中, expect
解决了旧语法的几个问题。 Check out this summary from RSpec about why.查看 RSpec 中关于原因的摘要。
It turned out being that I needed to define a subject
in the spec.结果是我需要在规范中定义一个
subject
。 I had only seed the error that related to this as reflect_on_assocation
.我只将与此相关的错误播种为
reflect_on_assocation
。
So for clarification, I just added所以为了澄清,我只是添加了
subject { Model.new }
and it worked:P subject { Model.new }
并且有效:P
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.