Rails 5:当我也对模型进行验证时,如何在数据库级别测试唯一性?
Rails 5: How do I test for uniquess at the database level when I also have validations on the model?
我有以下加入 table:
class ContactFormUsership < ApplicationRecord
belongs_to :user
belongs_to :contact_form
validates :user_id, presence: true, uniqueness: { scope: :contact_form_id }
end
它确保在创建行时没有重复的 user
/contact_form
对。
我在 table 上也有索引,以确保数据库级别的唯一性:
t.index ["user_id", "contact_form_id"], name: "index_contact_form_userships_on_user_id_and_contact_form_id", unique: true
我有一个如下所示的回归测试:
test 'An error is raised if a user is added to a form more than once' do
contact_form = ContactForm.create
user = users(:user_1)
assert_raises(ActiveRecord::RecordInvalid) do
2.times do
contact_form.users << user
end
end
end
但这并没有测试不可能在数据库级别创建重复行。它只测试验证。
如何在数据库级别测试唯一性?有什么方法可以 <<
无需验证吗?
由于您正在尝试测试您的 ContactFormUsership table 的行为,您将执行如下操作:
test 'An error is raised if a user is added to a form more than once' do
contact_form = ContactForm.create
user = users(:user_1)
assert_raises(ActiveRecord::RecordInvalid) do
c1 = ContactFormUsership.new(user: user, contact_form: contact_form)
c1.save
c2 = ContactFormUsership.new(user: user, contact_form: contact_form)
c2.save(validate: false)
end
end
您可以在 https://api.rubyonrails.org/classes/ActiveRecord/Validations.html
找到有关 validate: false 的更多信息
我有以下加入 table:
class ContactFormUsership < ApplicationRecord
belongs_to :user
belongs_to :contact_form
validates :user_id, presence: true, uniqueness: { scope: :contact_form_id }
end
它确保在创建行时没有重复的 user
/contact_form
对。
我在 table 上也有索引,以确保数据库级别的唯一性:
t.index ["user_id", "contact_form_id"], name: "index_contact_form_userships_on_user_id_and_contact_form_id", unique: true
我有一个如下所示的回归测试:
test 'An error is raised if a user is added to a form more than once' do
contact_form = ContactForm.create
user = users(:user_1)
assert_raises(ActiveRecord::RecordInvalid) do
2.times do
contact_form.users << user
end
end
end
但这并没有测试不可能在数据库级别创建重复行。它只测试验证。
如何在数据库级别测试唯一性?有什么方法可以 <<
无需验证吗?
由于您正在尝试测试您的 ContactFormUsership table 的行为,您将执行如下操作:
test 'An error is raised if a user is added to a form more than once' do
contact_form = ContactForm.create
user = users(:user_1)
assert_raises(ActiveRecord::RecordInvalid) do
c1 = ContactFormUsership.new(user: user, contact_form: contact_form)
c1.save
c2 = ContactFormUsership.new(user: user, contact_form: contact_form)
c2.save(validate: false)
end
end
您可以在 https://api.rubyonrails.org/classes/ActiveRecord/Validations.html
找到有关 validate: false 的更多信息