samedi 7 novembre 2020

Factorybot return same attributes when using an helper

Created a helper to read the csv file and provide an object with random geojson data.

When I call this helper in rails console I get random location data as expected.

# 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

But when I use it inside a Factory Bot factory, building or creating a factory always return the same location data.

# 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

Then using it in the seed file, it creates records with the same location data How can I have new location data on each factory instanciation ? What did I missed ?

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



Aucun commentaire:

Enregistrer un commentaire