2015-12-01 4 views
6

私はかなりチャンクなFactory Girl特性を持っており、パラメータを受け取り、has_many関係を作成しています。私はその形質を別の形質の一部として呼ぶことができ、形質を乾燥させたり、形質を工場に渡す際に形質を一緒に束ねることを容易にすることができます。どのようにすればよいかわからないのは、私が別の形質から呼び出すときに、パラメータを形質に渡す方法か、代わりに何をするかです。factory_girlのparamsを持つ別の特性から特性を呼び出してください

FactoryGirl.define do 
    factory :currency do 
    name Forgery::Currency.description 
    sequence(:short_name) { |sn| "#{Forgery::Currency.code}#{sn}" } 
    symbol '$' 
    end 

    factory :price do 
    full_price { 6000 } 
    discount_price { 3000 } 
    currency 
    subscription 
    end 

    sequence(:base_name) { |sn| "subscription_#{sn}" } 

    factory :product do 
    name { generate(:base_name) } 
    type { "reading" } 
    duration { 14 } 


    trait :reading do 
     type { "reading subscription" } 
    end 

    trait :maths do 
     type { "maths subscription" } 
    end 

    trait :six_month do 
     name { "six_month_" + generate(:base_name) } 
     duration { 183 } 
    end 

    trait :twelve_month do 
     name { "twelve_month_" + generate(:base_name) } 
     duration { 365 } 
    end 

    factory :six_month_reading, traits: [:six_month, :reading] 
    factory :twelve_month_reading, traits: [:twelve_month, :reading] 

    trait :with_price do 
     transient do 
     full_price 6000 
     discount_price 3000 
     short_name 'AUD' 
     end 

     after(:create) do |product, evaluator| 
     currency = Currency.find_by(short_name: evaluator.short_name) || 
        create(:currency, short_name: evaluator.short_name) 
     create_list(
      :price, 
      1, 
      product: product, 
      currency: currency, 
      full_price: evaluator.full_price, 
      discount_price: evaluator.discount_price 
     ) 
     end 
    end 

    trait :with_aud_price do 
     with_price 
    end 

    trait :with_usd_price do 
     with_price short_name: 'USD' 
    end 
    end 
end 

create(:product, :with_aud_price) # works 
create(:product, :with_usd_price) # fails "NoMethodError: undefined method `with_price=' for #<Subscription:0x007f9b4f3abf50>" 

# What I really want to do 
factory :postage, parent: :product do 
    with_aud_price full_price: 795 
    with_usd_price full_price 700 
end 

答えて

6

:with_price特性、すなわちこれに代えて、あなたが設定している他の属性とは別の行にする必要があります:

trait :with_usd_price do 
    with_price short_name: 'USD' 
end 

使用この:私は「

trait :with_usd_price do 
    with_price 
    short_name: 'USD' 
end 
+0

私はそれがなぜ機能するのか本当に分かりませんが、私は非常にうれしく思います。 – jim

+0

推測すると、フードの下では、特性B内の特性Aを特性Bの特性Aのサブクラスにしているように見える。これは多重継承を支持し、両方の特性が同じ過渡特性などを定義するならば何が起こるかを知っている。最初または最後のものが優先されると推測します。ファクトリで使われている 'parent::foo'のようなものではなく、メソッド呼び出しのような継承を定義するのに驚くようです。 – jim

+0

このことをさらに見てきましたが、これまでのところ良いことでしたが、OPのコードサンプルの一番下に例はありません。このフォームで試してみると、 'FactoryGirl :: AttributeDefinitionError:Attribute already defined:full_price'が得られます。うーん...私は一時的なプロパティの配列で動作させることができるかもしれません。 – jim

0

m on factory_bot 4.8.2と私のために働くものは次の通りです:

trait :with_usd_price do 
    with_price 
    short_name 'USD' 
end 
関連する問題