Factory Girl sequences not incrementing

可紊 提交于 2019-11-29 04:03:29

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!