在 RSpec 僵尸测试中,我正在尝试让此测试通过
describe Zombie do
it "starts off with two weapons" do
z = Zombie.new(:name => "Ash")
z.weapons.count.should == 2
end
end
为此,我利用 after_initialize 模型回调来创建(“构建”)武器
class Zombie < ActiveRecord::Base
after_initialize :grant_two_weapons
def grant_two_weapons
self.weapons.build(:name => "axe")
self.weapons.build(:name => "stick")
end
end
现在测试尚未通过,但还有一个问题,即标题中的问题。所以在 Rails 控制台中...
z = Zombie.new
z.weapons
#=> [#<Weapon id: nil, name: "axe", zombie_id: nil, created_at: nil, updated_at: nil>, #<Weapon id: nil, name: "stick", zombie_id: nil, created_at: nil, updated_at: nil>]
看起来我们得到了测试中描述的我们想要的东西,但是当我这样做时:
z.weapons.count
#=> 0
因此测试失败。这个有 2 个实体的数组的计数为何为 0?这是一个围绕“构建”等的 Rails 问题,但它也是一个 ruby 问题。该数组中有两个实体,但 ruby 似乎对它“撒谎”
最佳答案
这就是 count
的工作方式,它在数据库中执行 SQL 计数,但您的记录尚未保存,因此它给出零。
z.weapons.size
或 z.weapons.length
将为您提供您所期望的。
例如:http://rhnh.net/2007/09/26/counting-activerecord-associations-count-size-or-length
关于ruby-on-rails - 当在rails中使用 'build'命令时,在保存之前,我的zombie.weapons数组中有2个武器,但是zombie.weapons.count = 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15177421/