Rails 5:当我也对模型进行验证时,如何在数据库级别测试唯一性?

时间:2018-09-12 18:07:05

标签: ruby-on-rails minitest

我有以下联接表:

class ContactFormUsership < ApplicationRecord
  belongs_to :user
  belongs_to :contact_form

  validates :user_id, presence: true, uniqueness: { scope: :contact_form_id }
end

当创建一行时,它确保没有重复的user / contact_form配对。

我在该表上也有索引,以确保数据库级别的唯一性:

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

但是,这不能测试不可能在数据库级别创建重复的行。它仅测试验证。

如何在数据库级别测试唯一性?有没有办法未经验证就<<

1 个答案:

答案 0 :(得分:2)

由于您要测试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

您可以在Source处找到有关validate的更多信息:false