Using a factory girl to create a has_many relationship sign

I am looking for DBMS my test suite. Trying to create a tag that represents the specific values โ€‹โ€‹of the has_many relationship in the parent factory. Ideally, these values โ€‹โ€‹will be created from a separate factory.

I want to do something like this:

factory :room do
  trait :bathroom do 
    type :bathroom
  end
end

factory :house do 
  trait :one_bathroom do 
    association, :rooms, factory: [:room, :bathroom]
  end
end

The above should work if the relationship between the house and the room was from 1 to 1. But the House and the room have a relationship from one to many, so there are many rooms in the House. Based on this example, I would like to create a house in which there were many rooms with one bathroom.

Any ideas?

+4
source share
1 answer

" ", - :

factory :room do
  factory :bathroom do
    type :bathroom
  end
  factory :bedroom do
    type :bedroom
  end
end

factory :house do
  ignore do
    num_bathrooms 0
    num_bedrooms 0
  end

  trait :two_bathrooms do
    num_bathrooms 2
  end

  trait :three_bedrooms do
    num_bedrooms 3
  end

  after(:create) do |house, evaluator|
    create_list(:bathroom, evaluator.num_bathrooms, house: house)
    create_list(:bedroom, evaluator.num_bedrooms, house: house)
  end
end

. .

+7

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


All Articles