【问题标题】:How to get a list of traits passed to a factory_girl method?如何获取传递给 factory_girl 方法的特征列表?
【发布时间】:2014-06-15 00:19:22
【问题描述】:
#spec
let(:price) { create :price,:some_trait,:my_trait }

#factory
FactoryGirl.define do
  factory :price, class: 'Prices::Price' do
    ...

    after(:build) do |p,e|

      # How I can get the traits passed to the create method?
      # => [:some_trait,:my_trait]

      if called_traits_does_not_include(:my_trait) # fake code
        build :price_cost,:order_from, price:p
      end
    end

    ...
  end
end

如何在工厂的after(:build) 回调中获取传递给create 的特征?

【问题讨论】:

    标签: ruby rspec factory-bot


    【解决方案1】:

    我不知道有明确支持此功能的 factory_girl 功能。但我可以想到两种可能在特定情况下有效的部分解决方案:

    1. 在 trait 中设置一个瞬态属性:

      trait :my_trait do
        using_my_trait
      end
      
      factory :price do
        transient do
          using_my_trait false
        end
      
        after :build do |_, evaluator|
          if evaluator.using_my_trait
            # Do stuff
          end
        end
      
      end
      

      此方法需要您要跟踪的每个特征的瞬态属性。

    2. 如果您不需要知道 after :build 回调中使用了哪些特征,但您想跟踪多个特征而不为每个特征添加瞬态属性,请将特征添加到 after :build 回调中的列表中特点:

      trait :my_trait do
        after :build do |_, evaluator|
          evaluator.traits << :my_trait
        end
      end
      
      factory :price do
        transient do
          traits []
        end
      
        before :create do |_, evaluator|
          if evaluator.traits.include? :my_trait
            # Do stuff
          end
        end
      
      end
      

      (特征中的回调在工厂中的相应回调之前运行,因此如果您在其回调中最早注意到一个特征,您可以在before :create 中看到它。)如果您想跟踪,这可能比第一种方法更好许多工厂中的特征,这会使为每个特征添加瞬态属性更加痛苦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多