围绕已经存在的值编写工厂

发布于 2024-12-13 22:32:09 字数 418 浏览 0 评论 0原文

当我想测试一个想法时,我一直在使用 Factory Girl 在开发中创建一些基本对象,并且通常会遇到这种情况:

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken, Login has already been taken

如果我在开发模式下运行 FactoryGirl.create :user一次并将该用户留在数据库中,如果我在关闭控制台后再次尝试执行此操作,则必须运行该命令两次。基本上,序列在控制台实例之间重置。

有没有人想出一种方法来编写工厂,以便它们每次都会生成独特的结果?我知道我可以使用随机生成器从大域中选择一个值,从而最大限度地减少冲突的可能性。不过,如果有的话,我想找到一种更干净的方法。

I've been using Factory Girl to create some basic objects in development when I want to test out an idea, and I commonly run into this:

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken, Login has already been taken

If I've run FactoryGirl.create :user in development mode once and left that user in the db, I'll have to run that command twice if I try to do this again after closing the console. Basically, sequences are getting reset between console instances.

Has anyone come up with a way to write factories such that they'll generate unique results each time? I'm aware that I can use random generators to pick a value from a large domain, minimizing the chance of a collision. I'd like to find a cleaner method, if available, though.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烛影斜 2024-12-20 22:32:09

您可以为此编写一个序列。

Factory.sequence(:email) do |n|
  "tester#{n}@example.com"
end

Factory.define :user do |f|
  f.name "Tester"
  f.email {Factory.next :email}
  f.password "tester"
end

资料来源:大约在页面的一半位置。

编辑

-阅读,您似乎正在尝试在开发模式下创建数据。

您应该为此使用 seeds.rb 文件并维护一个计数器。

index = User.count || 1

User.create([
  {:email => "user#{index++}@example.com",
   :password => "password"},
  {:email => "user#{index++}@example.com",
   :password => "password"}
])

You can write a sequence for this.

Factory.sequence(:email) do |n|
  "tester#{n}@example.com"
end

Factory.define :user do |f|
  f.name "Tester"
  f.email {Factory.next :email}
  f.password "tester"
end

Source: about half way down the page.

EDIT

Upon re-reading, it seems that you are trying to create the data in development mode.

You should use the seeds.rb file for this and maintain a counter.

index = User.count || 1

User.create([
  {:email => "user#{index++}@example.com",
   :password => "password"},
  {:email => "user#{index++}@example.com",
   :password => "password"}
])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文