【问题标题】:FactoryGirl Rspec and SQLite3::ConstraintExceptionFactoryGirl Rspec 和 SQLite3::ConstraintException
【发布时间】:2012-04-17 04:22:47
【问题描述】:

我正在尝试创建一些关联的工厂,但事件不起作用:

factories.rb

  factory :user, class: User do
    first_name 'John'
    last_name 'Doe'
    email { "#{first_name}.#{last_name}@example.com".downcase } 
    username 'johndoe'
    password 'johndoe'
    password_confirmation 'johndoe'

    association :account_id, factory: :account 
  end

  factory :account, class: Account do
    #id is the only field
  end

  factory :event, class: Event do
    name 'Go to the Dentist'
    start_date "#{Time.now.next_month}"  
    end_date "#{Time.now+1.hour.next_month}" 
    copyright "#{Time.now.year}" 

    association :account_id, factory: :account  
  end 

controller_spec.rb

before(:each) do
  @request.env["devise.mapping"] = Devise.mappings[:user]
  @user = FactoryGirl.create(:user_profile, :username => 'johndoe' )
  sign_in @user
  @acct = FactoryGirl.create(:account, :id => @user.account_id)
  @event = FactoryGirl.create(:event, :account_id => @acct.id)
end

但这条事件线是一切都出错的地方。即使我使用@user.account_id 为事件设置:account_id,它也会失败并出现以下错误:

Failure/Error: @event = FactoryGirl.create(:event, :account_id => @acct.id)
     ActiveRecord::StatementInvalid:
       SQLite3::ConstraintException: constraint failed: INSERT INTO "event" ("account_id", "copyright", "created_at", "deleted", "end_date", "info", "name", "start_date", "type", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
     # ./spec/controllers/controller_spec.rb:13:in `block (3 levels) in <top (required)>'

非常感谢您对此提供的任何建议!

【问题讨论】:

  • 一个检查的地方可能是架构文件。如果为事件表指定了任何约束(在工厂中没有处理),那么它可能会抛出一个 ConstraintException。

标签: ruby-on-rails-3 rspec factory-bot


【解决方案1】:

我认为您收到约束异常的原因是您的表中已经有一些数据与您尝试添加的信息相冲突。

您可能想删除所有数据,然后尝试 rspec 测试用例。

【讨论】:

  • 在这种情况下我没有固定装置或任何东西。我所拥有的只是这几个要测试的工厂。怎么会有冲突?
  • 好吧,您可以通过命令行测试或其他方式将数据添加到数据库中。您可以使用 sqlite 浏览器查看您的数据库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
相关资源
最近更新 更多