在FactoryGirl中获取belongs_to关联以正常工作

时间:2013-04-02 19:46:35

标签: ruby-on-rails ruby mongoid factory-bot

我正试图让FactoryGirl中的协会发挥作用,他们只是......不这样做。我基本上得到了这个:

class Foo
  include Mongoid::Document

  belongs_to :bar
end

class Bar
  include Mongoid::Document

  has_many :foos
end

FactoryGirl.define do
  factory :foo, class => Foo do
    bar
  end

  factory :bar, class => Bar do
  end
end

至少所以文档引导我相信......但是在我的测试中,我有

a_foo=FactoryGirl.create :foo
a_foo.bar # Hooray! It's an associated object
Foo.where( _id: a_foo._id ).includes( :bar ).first.bar # This is nil!

为什么最后一行的关联值为零?我不需要它,因为正在测试的实际代码也做同样的事情,它有权期望它工作......我错过了为什么这不能正常工作?也许与热切加载有关?

1 个答案:

答案 0 :(得分:0)

您的代码实际上适用于FactoryGirl 4.2.0,Mongoid 3.0.9。但是当我运行mongoid且禁用了identitymap时(这是默认行为),我遇到了类似的问题。如果没有identitymap,您可以使用两个不同的ruby对象来表示数据库中的同一文档,彼此不同步。因此,如果您关闭了autosave,这可能会导致您遇到的问题。

尝试将您的简化代码自己粘贴到rails控制台中 - 如果它可以正常工作,那么您可能会更改配对实际代码的重要事项。 (很抱歉指出显而易见的事实,但是您的工厂代码中存在语法错误这一事实让我觉得您实际上没有测试过您的示例代码。)