我有一个班级
Gate < ActiveRecord::Base
self.inheritance_column = :kindof
# some methods
end
# and derived
MoneyHaters < Gate
# some overloaded methods
end
带有type column:kindof for STI 。
Durning测试我想创建一个2-3个孩子。主要是因为每个派生类在应用程序中必须是唯一的。像那样:
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工厂来创建对象,但是,如果这是不可能的 - 我想知道其他方法是什么。
非常感谢任何帮助。
答案 0 :(得分:0)
好的,我在发布问题前花了大约两个小时,但我发现只有在发布=)后才能找到答案
我只需要在属性的一个中移动类定义。
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