Gabriel Carneiro
Gabriel Carneiro

Reputation: 85

Why my Association using Factory Bot is not working?

I am using Factory Bot to specify the association between two models, vehicles and documents. A vehicle has_many documents and a document belongs_to vehicle. They are as it follows :

#spec/factories/vehicles.rb

    FactoryBot.define do
      factory :vehicle do
        user { nil }
        vehicle_model
        vehicle_color
        vehicle_type { FactoryBot.build(:vehicle_type, name:"Terrestre") }
        vehicle_year
        identifier { 'MyString' }
        status { :active }
        category
    
      end 
    end

#spec/factories/documents.rb
FactoryBot.define do
  factory :document do
    vehicle { nil }
    status { 'valid_file' }
    name { 'CRLV' }
  
  end
end

In this project I have a role driver that will need of an active vehicle document(this is the association that I want to build) to ride. I inserted byebug in the point of the code that I want to check. Firstly I checked if the vehicle is activated, so I typed : driver.active_vehicle, and I received :

#<Vehicle id: 2, user_id: 2, identifier: "MyString", created_at: "2020-07-20 16:57:22", updated_at: "2020-07-20 16:57:22", status: "active", category_id: 2, vehicle_model_id: 3, vehicle_color_id: 2, vehicle_type_id: 6, vehicle_year_id: 2>

Secondly I checked if the association is happening, so I typed : driver.active_vehicle.documents and I received the following return :

#<ActiveRecord::Associations::CollectionProxy []>

It's empty. Why this happened and how can I fix it ?

Upvotes: 0

Views: 1604

Answers (1)

Jon
Jon

Reputation: 10898

Your factory isn't called vehicles it's called vehicle.

Use it like this:

FactoryBot.create(:vehicle, :with_document)

Also, you added your :with_document trait to the document factory, rather than the vehicle factory as per your usage.

Upvotes: 0

Related Questions