我对rails很新,很抱歉,如果这个问题很愚蠢。我有一个模特:
class User < ActiveRecord::Base
end
class Lesson < ActiveRecord::Base
has_many :translations, dependent: :destroy
validates :title, presence: true,
length: {minimum: 5}
end
class Translation < ActiveRecord::Base
belongs_to :lesson
validates :first_language, presence: true
validates :second_language, presence: true
end
我为用户模型编写了最简单的测试:
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "should always pass" do
assert true
end
end
当我运行测试时出现错误:
rake test test/models/user_test.rb
Run options: --seed 24598
Running:
E
Finished in 0.055609s, 17.9827 runs/s, 0.0000 assertions/s.
1) Error:
UserTest#test_should_be_valid:
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: PRIMARY KEY must b
e unique: INSERT INTO "lessons" ("id", "title", "description", "words_qty", "cre
ated_at", "updated_at") VALUES (1, 'MyString', 'MyText', 1, '2014-11-12 22:09:52
', '2014-11-12 22:09:52')
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
为什么尝试用这些数据填充Lessons表?这个错误来自哪里?我在测试之前检查了Lessons表是空的。
好的,我想通了:这是因为test / fixtures / lessons.yml中的重复id。在测试开始时添加了两行具有相同id的行来测试数据库并导致此错误。
答案 0 :(得分:0)
检查Rails项目中的文件test/fixtures/lessons.yml
- 这定义了测试可以使用的测试数据。可以在那里定义2个具有相同ID的测试课程。