除非访问对象,否则ActiveRecord :: Persistence #reload不会重新加载对象

时间:2013-03-22 01:34:45

标签: ruby-on-rails activerecord rspec

我有一个方法可以创建一个或多个新的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个。相反,它会两次返回原始值。

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

# 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对象有什么特别之处?

0 个答案:

没有答案