Using FactoryGirl to create objects with the necessary associations

I am looking for advice on how to effectively use the FactoryGirl ruby ​​stone when working with objects that have many necessary related objects.

For example, let's say I have the following relationships between my classes.

class A < ActiveRecord has_many B end class B < ActiveRecord belongs_to A has_many C end class C < ActiveRecord belongs_to B end 

Now, if I wanted to write test cases for my C controller, I would have to create all the objects in this chain. Right now, what am I doing in my factories. But is there a better way?

+4
source share
1 answer

If you have your factories configured as follows:

 FactoryGirl.define do factory :library do name "Chicago Public Library" street_address "123 Morgan St." end factory :book do title "A Great Book" author "Mandy Yeats" association :library end factory :page do page_number 123 association :book end end 

Whenever you instantiate a page: in your tests, FactoryGirl will also create an instance: book and: library. You do not need to create a library and a book first. If you create a book: a library will also be created for the test :. You can use these instances in your tests as follows:

 page.book.library.name # after using FactoryGirl.create(:page) page.book.author book.library.street_address # after using FactoryGirl.create(:book) 

This is the easiest way to do this that I found.

+7
source

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


All Articles