Ruby on rails 使用';构建';rails中的命令,在保存之前,我的zombie.wearms数组中有2个武器,但是zombie.wearms.count=0
在针对僵尸的RSpec测试中,我试图通过这个测试Ruby on rails 使用';构建';rails中的命令,在保存之前,我的zombie.wearms数组中有2个武器,但是zombie.wearms.count=0,ruby-on-rails,ruby,arrays,rspec,model-associations,Ruby On Rails,Ruby,Arrays,Rspec,Model Associations,在针对僵尸的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_i
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
因此测试失败。此包含2个实体的数组的计数如何为0?这是一个围绕“构建”等的rails问题,但也是一个ruby问题。该数组中有两个实体,但ruby似乎在“撒谎”这就是
count
的工作方式,它在数据库中执行SQL计数,但您的记录尚未保存,因此它为零
z.wearms.size
或z.wearms.length
将满足您的期望
例如,检查一下:根据,有一些文档说明,如果定义为您所做的,则在初始化之后将被忽略
然而,似乎海报观察到的行为与该文档相冲突,因此YMMV。(这可能取决于您使用的Rails版本,但这只是猜测。)
我希望我能给出一个更明确的答案,但希望这能成为更熟悉初始化后行为的人的跳板。我能够通过调用self.save的“grant_two_武器”方法通过测试,但理论问题仍然存在,我觉得我不知何故作弊才通过了测试
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