当我使用pry在控制台中调试时,我运行了brief = Factory(:brief,:project => Factory(:project))这个命令。它应该可以正常工作,但是我收到了这个错误。
ActiveRecord::RecordNotUnique: PG::Error: ERROR: duplicate key value violates unique constraint "index_briefs_on_project_id"
DETAIL: Key (project_id)=(15389) already exists.
: INSERT INTO "briefs" ("project_id", "duration", "brand_name", "brand_info",
"customer_info", "competitor_info", "desired_impression", "competencies", "preferences",
"examples", "notes", "created_at", "updated_at", "channel_id") VALUES (15389, 14, NULL,
'brand info', NULL, NULL, NULL, NULL, NULL, NULL, NULL,
'2013-04-06 01:07:04.717364', '2013-04-06 01:07:04.717364', NULL) RETURNING "id"
为什么会出现此错误以及如何解决?
已编辑:我添加了工厂文件
brief_factory.rb
Factory.define :brief, :class => Brief do |b|
b.brand_info 'brand info'
b.duration 14
end
project_factory.rb
Factory.define :project, :class => Project do |p|
p.association :owner, :factory => :customer
p.title 'project title'
p.description 'project description'
p.stage :brief_completed
p.contest_type :standard
p.brief Factory.build(:brief)
p.association :project_type, :factory => :project_type
end
答案 0 :(得分:2)
看起来project
工厂正在自动创建brief
。所以Factory(:brief,:project => Factory(:project))
将尝试创建与同一项目相关的两个摘要。第二个失败是因为您对project_id
表中的briefs
列有唯一约束。
对于您定义的工厂,您可以在Pry中执行您想要做的事情:
project = Factory(:project)
brief = project.brief
或只是:
brief = Factory(:project).brief