【问题标题】:Rails: how can I assert that MySQL throws a duplicate entry errorRails:我如何断言 MySQL 会引发重复条目错误
【发布时间】:2014-07-28 20:59:18
【问题描述】:

我的 FooBar 表(在数据库级别)有一个唯一性约束。

# I have this in my migration
add_index :foo_bars, [:foo_id, :bar_id], :unique => true

我很高兴地告诉您,MySQL 可以完成它的工作,并且可靠地防止此表中出现重复条目​​。但是我该如何测试呢?这是我尝试过的:

test 'can not be a dup' do
  assert_no_difference('FooBar.count') do
    FooBar.create do |sc|
      sc.foo = foos(:one)
      sc.bar   = bars(:one)
    end
  end
end

运行时输出如下:

FooBar#test_can_not_be_a_dup:
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry '206867376-519457691' for key 'index_foo_bars_on_foo_id_and_bar_id'

所以测试没有完成。

我可以在事务或其他东西中运行我的测试,以 a) 确保它已回滚,b) 确保回滚的原因是 ActiveRecord::RecordNotUnique: Mysql2::Error?

或者我应该相信 MySQL/ActiveRecord 会支持我吗?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    固定:

    assert_raises ActiveRecord::RecordNotUnique do
      FooBar.create do |sc|
        sc.foo = foos(:one)
        sc.bar = bars(:one)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 1970-01-01
      • 2015-09-02
      • 2013-12-30
      • 2012-10-19
      • 1970-01-01
      • 2019-02-23
      • 2022-01-24
      • 2011-09-13
      相关资源
      最近更新 更多