代码之家  ›  专栏  ›  技术社区  ›  Sean Seefried

我正在使用Factory Girl中的序列来获取唯一值,但我得到了验证错误

  •  7
  • Sean Seefried  · 技术社区  · 15 年前

    我有一个这样定义的模型

    class Lga < ActiveRecord::Base
      validates_uniqueness_of :code
      validates_presence_of :name
    end 
    

    我为lgas定义了一个工厂

    Factory.sequence(:lga_id) { |n| n + 10000 }
    
    Factory.define :lga do |l|
      id = Factory.next :lga_id
      l.code "lga_#{id}"
      l.name "LGA #{id}"
    end
    

    但是,当我跑的时候

    Factory.create(:lga)
    Factory.create(:lga)
    

    在里面 script/console 我得到

    >> Factory.create(:lga)
    => #<Lga id: 2, code: "lga_10001", name: "LGA 10001", created_at: "2010-03-18  23:55:29", updated_at: "2010-03-18 23:55:29">
    >> Factory.create(:lga)
    ActiveRecord::RecordInvalid: Validation failed: Code has already been taken
    
    2 回复  |  直到 13 年前
        1
  •  7
  •   Sean Seefried    14 年前

    问题是 code name 属性不是所谓的 懒惰的特性 . 我想写些东西,比如:

    Factory.define :lga do |l|
      l.code { |n| "lga_#{n+10000}" }
    end
    

    但我想重复使用 名称 属性也是。你可以确保 比 id 每次评估 Factory.create 通过将其放入 after_build 钩子。

    Factory.define :lga do |l|
       l.after_build do |lga|
         id = Factory.next :lga_id
         lga.code = "lga_#{id}"
         lga.name = "LGA #{id}"
       end
    end
    

    这只适用于工厂女工1.2.3及以上版本。

        2
  •  2
  •   BookOfGreg    13 年前

    前面的答案仍然正确,但在新版《工厂女孩》中,您将收到警告。

    Factory.next has been depreciated. Use FactoryGirl.generate instead.
    

    新代码应该如下所示:

    Factory.define :lga do |l|
       l.after_build do |lga|
         id = FactoryGirl.generate :lga_id
         lga.code = "lga_#{id}"
         lga.name = "LGA #{id}"
       end
    end
    

    来源: http://notesofgreg.blogspot.co.uk/2012/07/foolproof-factorygirl-sequence.html