Factorybot return 使用助手时的相同属性

Factorybot return same attributes when using an helper

创建了一个帮助程序来读取 csv 文件并提供具有随机 geojson 数据的对象。

当我在 rails 控制台中调用这个助手时,我得到了预期的随机位置数据。

# LocationTestHelper
  def csv_data
    file_path = Rails.root.join('spec', 'factories', 'files', 'locations.csv')
    csv_text = File.read(file_path)
    CSV.parse(csv_text, headers: true)
  end

  def random_location
    nb_items = csv_data.length - 1
    index = Random.rand(0..nb_items)
    location = csv_data[index].to_hash
  end

但是当我在 Factory Bot 工厂内使用它时,建造或创建工厂总是 return 相同的位置数据。

# events.rb factory
require './spec/factories/scripts/location_importer'
FactoryBot.define do
  factory :event do
    location = LocationTestHelper.random_location
    address { location['street'] }
    city { location['city'] }
    country { location['country'] }
    latitude { location['latitude'] }
    longitude { location['longitude'] }
  end
end

然后在种子文件中使用它,它会创建具有相同位置数据的记录 我怎样才能在每个工厂实例中获得新的位置数据?我错过了什么?

# seeds.rb
 15.times do
    FactoryBot.create(:event)
  end
``
`

值得注意的是,一个工厂只在加载文件时被评估一次。因此,您的 location 以后不会再更改。

但是您可以使用 transient attribute:

来解决您的问题
FactoryBot.define do
  factory :event do
    transient do
      location { LocationTestHelper.random_location }
    end

    address { location['street'] }
    city { location['city'] }
    country { location['country'] }
    latitude { location['latitude'] }
    longitude { location['longitude'] }
  end
end