Can FactoryGirl verify that models already exist in the database before creating new ones?

I have the following factory setting:

FactoryGirl.define do factory :country do |f| f.name "USA" f.country_code "USA" f.currency_code "USD" end factory :region do |f| f.name "East Coast" f.country {Country.first} end factory :state do |f| f.name 'CA' f.region {Region.first} f.country {Country.first} end end 

What I want to do in the region and in state factories is to check if there is a record in the database for the country, if so, use it only if no records are found if it creates a new model.

Here is an example of what I mean, but not sure how to do it:

 factory :state do |f| f.name 'CA' f.region {Region.first || Factory(:region} f.country {Country.first || Factory(:state} end 

The reason I want to do this is to enter records in my database that will fill out the form selection fields, and I can check the use of the cucumber.

+4
source share
2 answers

You can use callbacks for this:

 FactoryGirl.define do factory :country do |f| f.name "USA" f.country_code "USA" f.currency_code "USD" end factory :region do |f| f.name "East Coast" after_build {|r| r.country = (Country.first || Factory(:country))} end factory :state do |f| f.name 'CA' after_build do |s| s.region = Region.first || Factory(:region) s.country = Country.first || Factory(:country) end end end 
+4
source

I think you need associations. each: region belongs to_to: state and each: state belongs to_to: a country which in turn has many states and regions.

Then you can use these associations in the factory.

Check out our getting started guide: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

0
source

Source: https://habr.com/ru/post/1386873/


All Articles