[英]Rails 5: How do I test for uniquess at the database level when I also have validations on the model?
I have the following join table: 我有以下联接表:
class ContactFormUsership < ApplicationRecord
belongs_to :user
belongs_to :contact_form
validates :user_id, presence: true, uniqueness: { scope: :contact_form_id }
end
It ensures that there are no duplicate user
/ contact_form
pairings when a row is created. 它确保在创建行时不存在重复的user
/ contact_form
配对。
I also have indexes on that table to ensure the uniquess on the db level: 我在该表上也有索引,以确保数据库级别的唯一性:
t.index ["user_id", "contact_form_id"], name: "index_contact_form_userships_on_user_id_and_contact_form_id", unique: true
I have a regression test that looks like this: 我有一个看起来像这样的回归测试:
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
But this does not test that it is not possible to create duplicate rows at the db level. 但是,这不能测试不可能在数据库级别上创建重复的行。 It only tests the validations. 它仅测试验证。
How do I test uniqueness at a db level? 如何在数据库级别测试唯一性? Is there any way to <<
without validations? 有没有办法<<
未经验证?
Since you are trying to test the behavior of your ContactFormUsership table, you would do something like: 由于您正在尝试测试ContactFormUsership表的行为,因此需要执行以下操作:
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
You can find out more about validate: false at https://api.rubyonrails.org/classes/ActiveRecord/Validations.html 您可以在https://api.rubyonrails.org/classes/ActiveRecord/Validations.html上找到有关validate的更多信息:false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.