Arne Cordes
Arne Cordes

Reputation: 581

FactoryGirl and getting an attribute-hash with all associations

I have two related models – Customer, which has one Address. These are my factories:

FactoryGirl.define do
  factory :customer do
    address
  end
end

FactoryGirl.define do
  factory :address do
    company_name "MyString"
    …
  end
end

In my controller spec, I try to get a hash for a customer which includes the address attributes… which just doesn´t work for me.

The first try was to use attributes_for(:customer), but that ignores any associations (as said in the documentation). After googling around I found the advice to use FactoryGirl.build(:customer).attributes.symbolize_keys, which should include association params. But not for me, I just get {"id"=>…, "created_at"=>…, "updated_at"=>…}. But customer.address.attributes outputs the correct hash, so the association seems to be correct.

So, I have a correct customer with a valid address and want to get a hash with all attributes, so I can test e. g. the creation of a customer in my controller spec.

post :create, {customer: !?!?!?}

Here are my models, for the sake of completion:

class Customer < ActiveRecord::Base
  has_one :address, foreign_key: :entity_id

  validates_presence_of :address
  accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
  belongs_to :customer, foreign_key: :entity_id
end

Upvotes: 1

Views: 247

Answers (1)

phoet
phoet

Reputation: 18845

This is not supported in FactoryGirl. Have a look at this issue here: https://github.com/thoughtbot/factory_girl/issues/359

I think this is not a really big issue. Just write this:

FactoryGirl.attributes_for(:customer, address: FactoryGirl.attributes_for(:address))

Upvotes: 1

Related Questions