Monday, October 15, 2012

SQL Unique Error while Unit Testing

Problem
You are just getting started on your development of a new rails application, and have created a couple of models using the rails generate scaffold command. Before you write your first real test case you verify the that the assertion fails, but instead you encounter:
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: PRIMARY KEY must be unique: INSERT INTO "courses" ("name", "number", "updated_at", "description", "id", "created_at", "departmentId") VALUES ('MyString', 'MyString', '2012-10-16 00:30:24', 'MyText', 1, '2012-10-16 00:30:24', 1)
What could have gone wrong? There's no data in your tables and your test case hasn't even used a model yet.

Solution
When ever creating a scaffold there is a fixture created with two data records which will look similar to the data below. For the simplest fix just change the the number for the unique identifier. In this case changing id: 1 on the second entry to id: 2  Another option is to fill the fixtures with data that is more relevant, this will help later down the line.

one:
  id: 1
  departmentId: 1
  number: MyString
  name: MyString
  description: MyText

two:
  id: 1
  departmentId: 1
  number: MyString
  name: MyString
  description: MyText



References:
http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures

No comments:

Post a Comment