FactoryGirl attributes_for with associations
Asked Answered
C

2

10

There is the following factory:

factory :car do
    name 'Some car'
    engine_value 1.6
    color '#ff0000'
    car_type
    engine_type
    transmission
    drive_type
    material
end

As you see there are a lot of associated objects. But code

attributes_for(:car)

generates only :name=>"Some car", :engine_value=>1.6, :color=>"#ff0000"} hash. I need to get a hash with all attributes. How can I do it? Thanks.

Campbellite answered 4/3, 2014 at 11:31 Comment(2)
possible duplicate of FactoryGirl: why does attributes_for omit some attributes?Vellavelleity
See also: #5104072Simplex
D
14

I've run into this same issue and I've used something like

build(:car).attributes

Not sure if this is the best way to do it but it worked for me

Hope this helps

Devlin answered 4/3, 2014 at 11:54 Comment(0)
E
0

You may want to omit the id, created_at and updated_at attributes.

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at')

If you need the keys to be symbols (as in the keys generated by attributes_for):

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at').symbolize_keys

Limitations:

  • It does not generate attributes for HMT and HABTM associations (as these associations are stored in a join table, not an actual attribute).
  • Association strategy in the factory must be create, as in association :user, strategy: :create. This strategy can make your factory very slow if you don't use it wisely.
Evette answered 3/7, 2017 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.