0

我有一种方法可以创建一个或多个新的 ActiveRecord 对象并将它们作为数组返回:

class Parent < ActiveRecord::Base

  has_many :children

  def build_children
    5.times do |i|
      Child.create
    end
    return children
  end

end

在为用户意外调用两次的极端情况编写规范时build_children,我注意到它并没有像预期的那样失败:

# passes
it "should return the previous batch of children if build_children called twice" do
  parent = Parent.create
  children = parent.build_children
  more_children = parent.build_children
  children.should == more_children
end

我认为这会失败,在第一次调用中返回 5 个孩子的数组,在第二次调用中返回 10 个。相反,它两次都返回原始的 5。

添加重新加载也不会使其失败!事实上,它似乎失败的唯一方法是如果我在重新加载后以某种方式访问​​返回的数组,比如打印它:

# this fails, as expected
it "should return the previous batch of children if build_children called twice" do
  parent = Parent.create
  children = parent.build_children
  parent.reload
  puts children
  more_children = parent.build_children
  children.should == more_children
end

更令人困惑的是,这一系列命令在控制台中按预期工作:

  parent = Parent.create
  children = parent.build_children
  parent.reload
  more_children = parent.build_children
  # => [ array of 10 children ]

reload在 rspec 示例组中的行为是否不同?访问实例化的 AR 对象有什么特别之处?

4

0 回答 0