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

Cra*_*ker 6 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
Run Code Online (Sandbox Code Playgroud)

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

Factory.define :foo do |foo|
  foo.attribute_a = "some random value"
  foo.attribute_b { |f| f.determine_attribute_b }
end
Run Code Online (Sandbox Code Playgroud)

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

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

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

gre*_*sen 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
Run Code Online (Sandbox Code Playgroud)

请记住这个新FactoryGirl语法。

  • 当前语法是 `after(:build) do` (5认同)