2014-04-02 95 views
0

我有更多的模型,其中有一個地址,有的只有address,有的同時有shipping_addressbilling_address。地址的方案是一樣的。在factory_girl中,我需要複製粘貼地址屬性的定義,但如果可以在這裏使用某種宏,那將會很好。factory_girl中的共享屬性

我想有這樣的事情:

factory :organization do 
    name   { Faker::Name.name } 
    # this could define street, city, zip, ... with prefix shipping_address 
    has_address :shipping_address 
emnd 

怎麼辦呢?

+0

地址可以去不同的列名?或者它的總是'shipping_address'? – apneadiving

+0

是的,它可以轉到具有不同前綴的列,所以有一個地址與街道,城市,郵編,...但它的前綴billing_address,shipping_address,等 – fifigyuri

+0

哦,列前綴。那我的回答就不好了!如果地址具有相同的模式,也許你可以將它們提取到他們自己的模型(和數據庫表)中,並使用關聯來代替? –

回答

1

我認爲使用特性有可能是一個很好的解決問題的方法:

require 'factory_girl' 
require 'active_model' 

class Person 
    include ActiveModel::Model 
    attr_accessor :name, :address 
end 

class Organization 
    include ActiveModel::Model 
    attr_accessor :name, :address 
end 

FactoryGirl.define do 
    factory :person do 
    name 'John Doe' 
    end 

    factory :organization do 
    name 'Some corp' 
    end 

    trait :with_address do 
    address '1234 Some road' 
    end 
end 

p FactoryGirl.build(:person, :with_address)  #=> #<Person:0x007f8d220baca0 @name="John Doe", @address="1234 Some road"> 
p FactoryGirl.build(:organization, :with_address) #=> #<Organization:0x007fc9a1a30008 @name="Some corp", @address="1234 Some road">