Shoulda-matchers: Scoped validate_uniqueness_of fails if the database has a foreign key constraint

Created on 7 Mar 2014  路  3Comments  路  Source: thoughtbot/shoulda-matchers

Here's the error I'm getting with the very latest master (fb77a6c310cdcbf3a15ac4e00ef59be5883342bb):

  2) Conversion should require case sensitive unique value for date scoped to note_id
     Failure/Error: it { should validate_uniqueness_of(:date).scoped_to(:note_id) }
     ActiveRecord::InvalidForeignKey:
       Mysql2::Error: Cannot add or update a child row: a foreign key constraint fails (`myapp_test`.`conversions`, CONSTRAINT `conversions_note_id_fk` FOREIGN KEY (`note_id`) REFERENCES `notes` (`id`)): INSERT INTO `conversions` (`amount`, `created_at`, `date`, `note_id`, `updated_at`) VALUES (0, '2014-03-07 15:54:00', 0, 0, '2014-03-07 15:54:00')

Most helpful comment

This is most likely due to the fact that we attempt to create a record for you with the validates_uniqueness_of matcher. You will probably need to create your own record before using the matcher.

it ' validates uniqueness' do
  #create a record however you prefer, we like FactoryGirl
  FactoryGirl.create(:conversion)
  #Or
  Conversion.create(myattributes)
  should validate_uniqueness_of(:data).scoped_to(:note_id)
end

All 3 comments

This is most likely due to the fact that we attempt to create a record for you with the validates_uniqueness_of matcher. You will probably need to create your own record before using the matcher.

it ' validates uniqueness' do
  #create a record however you prefer, we like FactoryGirl
  FactoryGirl.create(:conversion)
  #Or
  Conversion.create(myattributes)
  should validate_uniqueness_of(:data).scoped_to(:note_id)
end

Ok that totally worked with factory_girl, thanks :sunglasses:

:smile: Excellent! Glad I could help!

Was this page helpful?
0 / 5 - 0 ratings