在测试期间创建一些 class (STI)

Creating some class during tests (STI)

我有一个class

Gate < ActiveRecord::Base
  self.inheritance_column = :kindof
# some methods
end
#  and derived
MoneyHaters < Gate
# some overloaded methods
end

STI.

类型列 :kindof

在测试期间我想创建 2-3 个孩子。主要是因为每个派生的 class 在应用中必须是唯一的。像那样:

factory :gate do
  before(:create) do
    gate_name  = FFaker::Company.name.gsub( /\s+/,'' )
    gate_class_name = gate_name.singularize.classify
  end

  name { gate_name }

  # I want that next class will be declared in App namespace, like all others.
  gate_class  = Class.new(Gate) do
    def comission_in(amount)
      amount * 0.01 + 5
    end
    def comission_out(amount)
      amount * 0.02 + 5
    end
  end
  Object.const_set( gate_class_name, gate_class )

  type { gate_class_name }
  country { FFaker::Address.country_code }
end

当 运行 和 rspec 行 "Object.const_set"

时代码给了我错误
TypeError: #<FactoryGirl::Declaration::Implicit:0x00000006a1af30 @name=:gate_class_name, @ignored=false, @factory=#<FactoryGirl::Definition:0x00000006ed6df8 @declarations=#<FactoryGirl::DeclarationList:0x00000006ed6dd0 @declarations=[#<FactoryGirl::Declaration::Dynamic:0x00000006ed6998 @name=:name, @ignored=false, @block=#<Proc:0x00000006ed69c0@[skipped]>>, #<FactoryGirl::Declaration::Implicit:0x00000006a1af30 ...>], @name=:gate, @overridable=false>, @callbacks=[#<FactoryGirl::Callback:0x00000006ed6a38 @name=:before_create, @block=#<Proc:0x00000006ed6ba0@[skipped]>>], @defined_traits=#<Set: {}>, @to_create=nil, @base_traits=[], @additional_traits=[], @constructor=nil, @attributes=nil, @compiled=false>> is not a symbol nor a string

但在 rails 控制台中工作正常

通常我会调用 FactoryGirl 工厂来创建 objects,但是,如果那是不可能的 - 我想知道有没有其他方法可以做到这一点。

非常感谢任何帮助。

好的,我花了大约两个小时才发布问题,但我在发布后才找到答案=)

我只需要将 class 定义移动到属性的定义中。

FactoryGirl.define do
  factory :gate do

    name { FFaker::Company.name }
    type { 
      class_name = 'Gate' + name.gsub( /[[:blank:][:cntrl:][:punct:]]/,'' ).to_s.singularize
      gate_class = class_name.classify
      class_instance  = Class.new(Gate) do
        def comission_in(amount)
          amount * 0.01 + 5
        end
        def comission_out(amount)
          amount * 0.02 + 5
        end
      end
      Object.const_set( gate_class, class_instance )
      puts " gate_class: '#{ gate_class }'; name: '#{ name }';"
      class_name
    }
    country { FFaker::Address.country_code }

  end
end