【发布时间】: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