加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在factory_girl中使用params从另一个特征中调

发布时间:2020-12-16 19:17:37 所属栏目:百科 来源:网络整理
导读:我有一个相当矮胖的工厂女孩??特质,接受参数并创建一个has_many关系.我可以称这种特性作为另一种特性的一部分来干燥特性,或者在将它们传递给工厂时更容易将特征捆绑在一起.我不知道怎么做的是当我从另一个特征中调用它或者做什么时,如何将params传递给一个特
我有一个相当矮胖的工厂女孩??特质,接受参数并创建一个has_many关系.我可以称这种特性作为另一种特性的一部分来干燥特性,或者在将它们传递给工厂时更容易将特征捆绑在一起.我不知道怎么做的是当我从另一个特征中调用它或者做什么时,如何将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

解决方法

:with_price特征需要与您正在设置的其他属性位于不同的行上,即代替:
trait :with_usd_price do
  with_price short_name: 'USD'
end

用这个:

trait :with_usd_price do
  with_price
  short_name: 'USD'
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读