使用FactoryGirl在RSpec中创建测试对象失败,并带有嵌套属性

时间:2011-07-21 14:32:37

标签: sqlite factory-bot nested-attributes rspec-rails

我有一个具有许多PerformedExercises的Workout模型,它有许多PeformedSet。我无法在测试中构建一个对象,我不确定它是SQLite3还是其他东西(它在测试环境之外工作正常)。

我有以下工厂:

FactoryGirl.define do
 factory :workout do
   title    'workout one'
   performed_exercise
 end

 factory :performed_exercise do
  exercise_id       '2'
  performed_set
 end

 factory :performed_set do
  set_number        '1'
 end
end

我的RSpec测试看起来是这样的(我让它变得非常简单,以便排除测试中的任何其他问题):

it "is causing me to lose hair" do
  wrkt = FactoryGirl.build(:workout)
end

当我运行测试时,收到以下错误消息:

Failure/Error: wrkt = FactoryGirl.build(:workout)
     ActiveRecord::StatementInvalid:
       SQLite3::ConstraintException: constraint failed: 
        INSERT INTO "performed_sets" ("created_at", "notes", "performed_exercise_id", "reps", "set_number", "updated_at", "weight") 
        VALUES (?, ?, ?, ?, ?, ?, ?)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

不要设置运动ID。让SQLite为你处理id。

factory :performed_exercise do
  performed_set
end