在依赖属性中调用FactoryGirl模型中的方法

时间:2012-01-04 23:07:52

标签: 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

在FactoryGirl 1.3中,我有一个看起来像这样的工厂:

Factory.define :foo do |foo|
  foo.attribute_a = "some random value"
  foo.attribute_b { |f| f.determine_attribute_b }
end

这很好用。 attribute_b是一个依赖于代码块的属性,它会将Foo的实际实例传递给变量f,并通过正确设置attribute_a来完成

我刚刚升级到FactoryGirl 2.3.2,这种技术不再适用。从上述等效代码中的f变量不再是Foo的实例,而是FactoryGirl::Proxy::Create的实例。此类似乎能够读取先前设置的属性(这样Dependent Attributes example in the docs仍然有效)。但是,它无法从构建的类中调用实际方法。

有没有办法可以使用旧版FactoryGirl的技术?我希望能够使用构建类的实例方法的结果来定义属性并设置其值。

1 个答案:

答案 0 :(得分:4)

您可以像这样使用回调after_createafter_build

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

请记住这种新的FactoryGirl语法。