Factory Girl sequences not incrementing

前端 未结 2 1993
执笔经年
执笔经年 2020-12-16 18:04

I\'m trying to get FactoryGirl to generate some names for me, but the sequence doesn\'t seem to increment.

# spec/factories/vessel.rb
require \'factory_girl\         


        
相关标签:
2条回答
  • 2020-12-16 18:13

    That works, bit it will mean that you can't override the name anywhere in the specs, because the after build hook will always run and overwrite any name.

    The reason your original example doesn't work is that you're invoking the sequence when the factory is defined, rather than when the factory is run. You can provide a block to attribute definitions which will be invoked every time the factory runs. This way, you get a chance to generate a value for each instance, rather than generating one value for all instances. This is most frequently used for sequences and times.

    You can fix your original example with this snippet:

    sequence :vessel_name do |n|
      "TK42#{n}"
    end
    
    factory :vessel do
      name { generate(:vessel_name) }
      vessel_type 'fermenter'
      volume_scalar 100.0
      volume_units 'bbl'
    end
    

    If all names can be generated with the same format, you could also leave out the value entirely by renaming your sequence:

    sequence :name do |n|
      "TK42#{n}"
    end
    
    factory :vessel do
      name
      vessel_type 'fermenter'
      volume_scalar 100.0
      volume_units 'bbl'
    end
    

    However, that won't work if you need different name formats for different factories.

    0 讨论(0)
  • 2020-12-16 18:15

    And the answer is:

    require 'factory_girl'
    
    FactoryGirl.define do
    
      sequence :vessel_name do |n|
        "TK42#{n}"
      end
    
      factory :vessel do
        vessel_type 'fermenter'
        volume_scalar 100.0
        volume_units 'bbl'
        after :build do |v|
          v.name = FactoryGirl.generate(:vessel_name)
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题