Ruby 从依赖属性中的FactoryGirl模型调用方法
我有一个类似于以下的模型:Ruby 从依赖属性中的FactoryGirl模型调用方法,ruby,factory-bot,Ruby,Factory Bot,我有一个类似于以下的模型: class Foo attr_accessor :attribute_a # Really an ActiveRecord attribute attr_accessor :attribute_b # Also an ActiveRecord attribute def determine_attribute_b self.attribute_b = some_biz_logic(attribute_a) end end 在Factor
class Foo
attr_accessor :attribute_a # Really an ActiveRecord attribute
attr_accessor :attribute_b # Also an ActiveRecord attribute
def determine_attribute_b
self.attribute_b = some_biz_logic(attribute_a)
end
end
在FactoryGirl 1.3中,我有一个工厂,看起来像这样:
Factory.define :foo do |foo|
foo.attribute_a = "some random value"
foo.attribute_b { |f| f.determine_attribute_b }
end
FactoryGirl.define do
factory :foo do
attribute_a "some random value"
after_build do |obj|
obj.attribute_b = obj.determine_attribute_b
end
end
end
这很管用attribute_b
是一个依赖于代码块的属性,它将被传递一个Foo
的真实实例到变量f
,并完成一个正确设置的attribute_a
我刚刚升级到FactoryGirl 2.3.2,这项技术不再有效。上述等效代码中的f
变量不再是Foo
的实例,而是FactoryGirl::Proxy::Create
。该类似乎能够读取以前设置的属性(这样该属性仍然有效)。但是,它不能从构建的类中调用实际的方法
我有没有办法使用FactoryGirl旧版本的技术?我希望能够使用生成类的实例方法的结果定义属性并设置其值。您可以在创建后使用回调
,在构建后使用回调,如下所示:
Factory.define :foo do |foo|
foo.attribute_a = "some random value"
foo.attribute_b { |f| f.determine_attribute_b }
end
FactoryGirl.define do
factory :foo do
attribute_a "some random value"
after_build do |obj|
obj.attribute_b = obj.determine_attribute_b
end
end
end
记住这个新的<代码> FaseMy/<代码>语法。顺便说一下,
顺便说一下,也许您应该考虑在前面调用CestEnEy属性Teb,在模型中创建回调。在工厂中为测试设置属性_b似乎是合理的。这是个不错的主意,但在我的实际代码中,我不能这么做。有时我想在控制器代码中单独设置它。当前语法是(:build)do之后的