Best way to establish nested associations with RSpec / FactoryGirl

I'm trying to create a test suite for a Rails application, and I'm not sure how to create objects using FactoryGirl (if necessary, I can switch to another tool).

The hard part is that there are deep nested associations, so you can take this part of the diagram: http://imgur.com/HAUS7kr

Let's say I want to do some tests in the "ItemTracker" model. Now there are 2 approaches:

  • To have a valid object, I will need to create a Connexion that needs a token, that needs a project, etc. In addition, I want the ProjectItem project to be the same as the project token. Same thing with company (top). I would not want 2 different projects or companies to be created. Therefore, I need these objects to share some associations. One of the drawbacks of this approach is that I'm not sure how to create unrelated several related objects, and I'm also going to build a ton of objects that I don't need (except for validations).

  • I could say, “for this particular test, associations are irrelevant, so I’ll just create one ItemTracker without its Connexion or ProjectItem and do my things with this isolated object.” In general, I would just create the objects and associations that I really need. While playing with the traits, I found a way to avoid creating associations if I don't need them. The disadvantage is that this object is invalid (there are confirmations about associations), so every time I am going to save something, I will have an exception that will hurt in some testing cases.

So, I think, my question is: what is the best way to configure some objects for testing in such a complex object structure?

Thanks for the feedback;)

+4
2

, , , with_all_relations, . :

FactoryGirl.define do
  factory :item_tracker do
    ...
    trait :with_all_relations do
      after(:build) do |item_tracker|
        company = create(:company)
        item = create(:item, company: company)
        user = create(:user, company: company)
        ...
        item_tracker.project_item = project_item
        item_tracker.connexion = connexion
      end
    end
  end
end

, - .

+1

, ProjectItem , . (). 2

"named" factory, initialize_with:

factory :project do
  # define common attributes for projects

  factory :project_1 do
    initialize_with do
      Project.find_or_create_by(name: "Project 1")
    end
  end
end

:

association :project, factory: project_1

.

, , , , , .

, . , , . , .

"" factory, , . , ( ) , . Jeiwan - .

+1

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


All Articles