FactoryGirl中带有块的多个参数

时间:2015-07-11 07:41:16

标签: ruby-on-rails ruby factory-bot

我在spec\factories\campaigns.rb中有一个方法:

def campaign_trait(name, *callback_attrs, &block)
  trait name do
    association :campaign_type, factory: [:campaign_type, name]

    after(:build) do |campaign, evaluator|
      eval_str = ""
      callback_attrs.each do |arg|
        arg = [arg] unless arg.is_a? Array

        method_name = arg.shift
        method_args = arg
        method_name = "add_#{method_name}" unless respond_to? method_name

        eval_str << method_name.to_s
        eval_str << "(campaign"
        eval_str << ", evaluator" if method_name == "add_campaign_scopes"
        if method_args.any?
          method_args.map! { |i| i.is_a?(Symbol) ? ":#{i}" : i }
          eval_str << ", " << method_args.map(&:to_s).join(', ')
        end
        eval_str << ")\n"
      end
      eval eval_str
    end

    yield(block) if block_given?
  end
end

我在这里打电话:

FactoryGirl.define do
    campaign_trait :basket, :campaign_scopes, [:banner, :basket] do
      initialize_with { Campaigns::Basket.new(attributes, without_protection: true) }
      emitent_article 'emitent'
      emitent_name 'Emitent'
    end
end

我面临的问题是,在方法campaign_trait中,我得到的callback_attrs等于[:campaign_scopes, []]而不是预期的[:campaign_scopes, [:banner, :basket]]

如果我在没有阻止的情况下致电campaign_trait,一切正常,我按预期得到[:campaign_scopes, [:banner, :basket]]

你能帮我吗?

1 个答案:

答案 0 :(得分:0)

问题是我通过多次测试多次调用campaign_trait并以某种方式(我不知道为什么),在测试之间共享callback_attrs。 method_name = arg.shift打破了修改callback_attrs的代码。

谢谢,BroiSatse!深度调试帮助了我。