使用 Factory Girl 创建具有独特属性的实例
我在 guid 字段上设置了约束和验证,以便每个字段都是唯一的。问题是,使用下面的工厂定义,我只能创建一个用户实例,因为其他实例无法通过验证。
如何正确执行此操作以使 guid 字段始终是唯一的?
Factory.define(:user) do |u|
u.guid UUIDTools::UUID.timestamp_create.to_s
end
I have a constraint and a validation placed on the guid field so that each is unique. The problem is, with the factory definition that I have below, I can create only one user instance, as additional instances fail validation.
How do I do this correctly so that the guid field is always unique?
Factory.define(:user) do |u|
u.guid UUIDTools::UUID.timestamp_create.to_s
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,Factory Girl 解决了序列的问题:
但是,我假设您不想要类似迭代器的东西,而是想要一个时间戳。
这可以使用惰性属性(在运行时评估)来完成:
或者,假设 UUIDTools::UUID.timestamp_create 生成一个(希望格式合适的)时间戳:
In general, Factory Girl addresses the problem with sequences:
I assume, however, that you do not want to have something iterator-like but a timestamp.
This could be done using lazy attributes (that evaluate at runtime):
Or, assuming that UUIDTools::UUID.timestamp_create generates a (hopefully suitably formatted) timestamp: