简体   繁体   中英

Factory girl association with more than one trait

I have a association like this :

association :address, :factory => [:address, :closer_address]

Where my factory is like this:

factory :address do
  address1 "12 Any Street"
  latitude 22.4583397
  longitude -11.06776
  state 'pending_verification'

  trait :closer_address do
    latitude 33.4783397
    longitude -11.06776
  end

  trait :verified do
    state 'verified'
  end
end

So can I somehow create an association with more than one trait? Or there is another way around it? The idea is that I want to have closer_address which is also verified, and in another case I might want closer_address which is not verified, so that's why keeping them separate.

Any ideas?

You could do this to have two different trait options:

  factory :address do
    address1 "12 Any Street"
    latitude 22.4583397
    longitude -11.06776
    state 'pending_verification'

    trait :closer_address do
      latitude 33.4783397
      longitude -11.06776
    end

    trait :verified_closer_address do
      latitude 33.4783397
      longitude -11.06776
      state 'verified'
    end
  end

You would create the objects like this:

:factory => [:address, :closer_address]

or this:

:factory => [:address, :verified_closer_address] 

Or you could do this without changing your current factory:

  factory :address do
    address1 "12 Any Street"
    latitude 22.4583397
    longitude -11.06776
    state 'pending_verification'

    trait :closer_address do
      latitude 33.4783397
      longitude -11.06776
    end

    trait :verified do
      state 'verified'
    end
  end

You would create the objects like this:

:factory => [:address, :closer_address, :verified]

It is possible to use multiple traits simultaneously when creating an object with FactoryGirl.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM