关联工厂的工厂女孩​​唯一性验证失败 [英] factory girl uniqueness validation fails for associated factories

查看:68
本文介绍了关联工厂的工厂女孩​​唯一性验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有(简化的)工厂,定义如下:

I have (simplified) factories defined as follows:

factory :league do
  acronym 'NBA'
end

factory :division do
  league
end

部门属于联盟.当我定义这个工厂时,我的假设是将创建1个联赛,并且该联赛将被一遍又一遍地重复使用,以给各部门一个真实的League_ID.

Divisions belong to Leagues. When I define this factory, it was my assumption that 1 league would be created, and that league would be reused over and over again to give divisions a real league_id.

相反,在FactoryGirl.create(:division)的第二次通话中出现错误,因为联赛acronym应该是唯一的.

Instead, I'm getting errors on the 2nd call of FactoryGirl.create(:division) because the League acronym is supposed to be unique.

class League < ActiveRecord::Base
  validates :acronym, uniqueness: true
end

导致以下测试中断

ActiveRecord :: RecordInvalid:验证失败:首字母缩略词已被使用

ActiveRecord::RecordInvalid: Validation failed: Acronym has already been taken

如何解决此问题,最好不要在测试设置中创建层次结构?

How can I work around this, preferably without creating a hierarchy in the setup to the test?

如果我要完成的工作比factory_girl好,请提出建议

If theres something better than factory_girl for what I'm trying to accomplish, please do suggest it

推荐答案

在联盟定义中使用initialize_with.

请参见 http://robots.thoughtbot.com/post/16196616388/factory-girl-2-5-gets-custom-constructors

然后您可以发出find_or_create_by_acronym以确保它被创建一次.

You could then issue find_or_create_by_acronym to guarantee it's created once.

这篇关于关联工厂的工厂女孩​​唯一性验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆