rails 运行 FactoryGirl 中每个 rake 任务的代码,实际上是每个环境负载

rails running code in FactoryGirl on every rake task, actually on every environment load

我们无法在新机器上 运行 rake db:schema:load 因为在某处为 rake 任务加载 Rails 环境时,正在调用一个 class 方法试图在 db 中访问一个 table,这显然还不存在。

我发现它来自 FactoryGirl 定义。

我们为其中的 2 个工厂设置了一个 location_id 变量到世界 location.id,就像这样

FactoryGirl.define do
  factory :some_model do
    ....
    ....
    cached_location_id Location.world.id
    ....
  end
end

所以当 rails 加载我们所有的代码时,它立即 运行 宁 Location.world。我认为这是 FactoryGirl 特有的。

如何解决?

因此,当工厂被要求使用 { } 创建模型时,只需将其更改为仅 运行 Location.world 代码,如下所示:

FactoryGirl.define do factory :some_model do .... .... cached_location_id {Location.world.id } .... end end

真是太棒了!