【发布时间】:2018-03-17 10:59:00
【问题描述】:
我有一个User 模型,它的子关联为items。项目的:name 对用户来说应该是唯一的,但它应该允许不同的用户拥有同名的项目。
Item 模型当前设置为:
class Item < ApplicationRecord
belongs_to :user
validates :name, case_sensitive: false, uniqueness: { scope: :user }
end
这可以验证用户内部,但仍然允许其他用户保存具有相同名称的项目。
如何使用 RSpec/Shoulda 进行测试?
我目前的测试写成:
describe 'validations' do
it { should validate_uniqueness_of(:name).case_insensitive.scoped_to(:user) }
end
但是这个测试失败了,因为:
Failure/Error: it { should validate_uniqueness_of(:name).scoped_to(:user).case_insensitive }
Item did not properly validate that :name is case-insensitively
unique within the scope of :user.
After taking the given Item, setting its :name to ‹"an
arbitrary value"›, and saving it as the existing record, then making a
new Item and setting its :name to a different value, ‹"AN
ARBITRARY VALUE"› and its :user to a different value, ‹nil›, the
matcher expected the new Item to be invalid, but it was valid
instead.
然而,这是我想要的行为(除了应该为用户选择 nil 的奇怪部分)。当用户不同时,同名应该是有效的。
可能是我没有正确使用范围测试,或者这对于 Shoulda 来说是不可能的,这里是 the description of scoped tests。在这种情况下,您将如何编写模型测试来测试这种行为?
【问题讨论】:
-
唯一性匹配器不支持使用关联作为作用域,有some issues in Github。作为一种解决方法,您应该使用
scoped_to(:user_id)。但是即使进行了这种更改,scope_to和case_insensitive似乎也不起作用。我认为这是一个错误。 @oneWorkingHeadphone 你会举报吗?否则我会做的。 -
@ana06 很好,谢谢!我将打开一个新问题并参考您链接的问题。
-
这个问题现在好像已经解决了