0

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?

1 Answer 1

2

Fixed:

assert_raises ActiveRecord::RecordNotUnique do
  FooBar.create do |sc|
    sc.foo = foos(:one)
    sc.bar = bars(:one)
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.