【问题标题】:Creating test objects in RSpec with FactoryGirl fails with Nested Attributes使用 FactoryGirl 在 RSpec 中创建测试对象失败并出现嵌套属性
【发布时间】:2011-07-21 14:32:36
【问题描述】:

我有一个锻炼模型,它有很多 PerformedExercises,它有很多 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 (?, ?, ?, ?, ?, ?, ?)

任何帮助将不胜感激!

【问题讨论】:

  • 我遇到了同样的问题 - 我想知道它是否是特定于 sqlite 的,因为我可以通过 postgres 在控制台(或应用程序)中运行相同的代码

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


【解决方案1】:

不要设置练习 ID。让 SQLite 为您处理 id。

factory :performed_exercise do
  performed_set
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    相关资源
    最近更新 更多