FactoryGirl Rspec和SQLite3 :: ConstraintException

时间:2012-04-05 18:17:29

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

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

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)>'

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

1 个答案:

答案 0 :(得分:0)

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

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