stephenmurdoch
stephenmurdoch

Reputation: 34603

Rails: how can I assert that MySQL throws a duplicate entry error

I've got a uniqueness constraint on my FooBar table (at the database level).

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

I'm pleased to say that MySQL does it's job, and reliably prevents duplicate entries in this table. But how can I test that? Here's what I've tried:

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

This runs with the following output:

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'

So the test is not completing.

Can I run my test inside a transaction or something, to a) ensure that it's rolled back, and b) ensure that the reason for the rollback is an ActiveRecord::RecordNotUnique: Mysql2::Error?

Or should I just trust MySQL/ActiveRecord to have my back on this?

Upvotes: 0

Views: 330

Answers (1)

stephenmurdoch
stephenmurdoch

Reputation: 34603

Fixed:

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

Upvotes: 2

Related Questions