Mike W
Mike W

Reputation: 401

Factorygirl set has_many as nil

I have a user factory that be default creates an association for user_document

FactoryGirl.define do
  factory :user do |u|
    sequence(:first_name) {|n| "firstname-#{n}" }
    after(:create) do |user|
      create(:user_document, document_type: :address_proof, user: user)
    end
  end
end

I'd like to define a new factory for which the association user_document is null. How do I do this ?

[UPDATE]

When I do this

  factory :user_with_no_doc_buyer do
    user_document nil
  end

I get an error saying :

 NoMethodError: undefined method `user_document=' for #<User:0x007f97329c08f8>

and When I do user_documents nil I get

NoMethodError: undefined method `each' for nil:NilClass

thanks

Upvotes: 0

Views: 394

Answers (2)

JK Gunnink
JK Gunnink

Reputation: 153

I'd create two traits.

FactoryGirl.define do
  factory :user do
    sequence(:first_name) {|n| "firstname-#{n}" }

    trait :with_document do
      after(:create) do |user|
        create(:user_document, document_type: :address_proof, user: user)
      end
    end

    trait :without_document do
      user_documents []
    end
  end
end

Then you just call whichever factory you need.

FactoryGirl.create(:user, :with_document) for example

Edit: Have seen you want the with document to be the default. That's easy enough. You can just use the code you have and take my suggestion of a trait without document which you can call when you need it.

Upvotes: 1

usha
usha

Reputation: 29349

Use traits

FactoryGirl.define do
  factory :user do |u|
    sequence(:first_name) {|n| "firstname-#{n}" }
    trait :with_user_document
      after(:create) do |user|
        create(:user_document, document_type: :address_proof, user: user)
      end
    end
  end
end

To create user with document

FactoryGirl.create(:user, :with_user_document)

To create user with null document

FactoryGirl.create(:user)

Upvotes: 1

Related Questions