我正在使用RSpec和FactoryGirl测试我的Ruby-on-Rails-3应用程序。我使用的是工厂的层次结构:
FactoryGirl.define do
factory :local_airport do
... attributes generic to a local airport
factory :heathrow do
name "London Heathrow"
iata "LHR"
end
factory :stansted do
name "Stansted"
iata "STN"
end
... more local airports
end
end在我的RSpec中,我有时希望能够通过指定父工厂来创建所有子工厂。理想情况下,如下所示:
describe Flight do
before( :each ) do
# Create the standard airports
FactoryGirl.find( :local_airport ).create_child_factories
end
end在此之前,非常感谢您。
发布于 2013-07-15 02:25:39
在钻研了几个小时的FactoryGirl代码之后,我找到了一个解决方案。有趣的是,FactoryGirl只在工厂中存储了对父级的引用,而不是从父级到子级的引用。
在spec/factory/factory_helper.rb中:
module FactoryGirl
def self.create_child_factories( parent_factory )
FactoryGirl.factories.each do |f|
parent = f.send( :parent )
if !parent.is_a?(FactoryGirl::NullFactory) && parent.name == parent_factory
child_factory = FactoryGirl.create( f.name )
end
end
end
end在我的RSpec中,我现在可以写:
require 'spec_helper'
describe Flight do
before( :each ) do
# Create the standard airports
FactoryGirl.create_child_factories( :local_airport )
end
...我发现的一个问题是,工厂层次结构最好是简单的(即两个级别)。我从一个三层的层次结构开始,发现我生成的“抽象”工厂只作为层次结构的一部分而存在。我已经使用特征将层次结构简化为两个级别。
发布于 2013-07-12 02:34:46
你不能真的告诉一个工厂构建它的所有子工厂,因为作为一个子工厂只是意味着它继承了父工厂的属性。但是您可以做的是添加一个特征,例如:with_child_factories。那么您的工厂将如下所示:
FactoryGirl.define do
factory :local_airport do
... attributes generic to a local airport
factory :heathrow do
name "London Heathrow"
iata "LHR"
end
factory :stansted do
name "Stansted"
iata "STN"
end
... more local airports
trait :with_child_factories do
after(:create) do
FactoryGirl.create(:heathrow)
FactoryGirl.create(:stansted)
...
end
end
end
end然后你可以在你的测试中调用它
FactoryGirl.create(:local_airport, :with_child_factories)https://stackoverflow.com/questions/17500741
复制相似问题