如何强制Forgery在Factory_girl定义中返回unqiue数据

kte*_*tec 2 rspec ruby-on-rails factory-bot ruby-forgery

我的工厂看起来像这样:

Factory.define :coupon do |c|
  c.title { Forgery(:lorem_ipsum).sentences(3, :random => true) }
end
Run Code Online (Sandbox Code Playgroud)

我从Rspec打来的电话看起来像这样:

coupons = []
5.times {|i| coupons << Factory(:coupon, :starts_at => i.days.ago) }
Run Code Online (Sandbox Code Playgroud)

使用我的优惠券模型,我有一个验证,要求标题是唯一的.我能够运行此测试的唯一方法是在我的工厂中执行此操作:

Factory.define :coupon do |c|
  c.title {|i| Forgery(:lorem_ipsum).sentences(3, :random => true) + "#{i}" }
end
Run Code Online (Sandbox Code Playgroud)

当然必须有更好的方法吗?

Jar*_*nen 5

我就是这样做的(使用新的Factory Girl语法):

FactoryGirl.define do
  factory :coupon do
    sequence(:title)     { |n| Forgery::LoremIpsum.words(n, :random => true) }
    sequence(:starts_at) { |n| n.days.ago } 
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在规范中创建优惠券:

coupons = FactoryGirl.create_list(:coupon, 5)
Run Code Online (Sandbox Code Playgroud)