Factory Girl Polymorphic has_many,belongs_to

时间:2012-11-05 02:33:43

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

class Food < ActiveRecord::Base
has_many :images, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy
end

class MenuPhoto < ActiveRecord::Base
has_one :image, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy
end

class Image < ActiveRecord::Base
belongs_to :imageable, foreign_key: :imageable_uuid, :polymorphic => true
end

我上面的这些模型使用多态。所以在我的工厂女孩​​,我这样做。

factory :food do
association :images, factory: :image
end

factory :menu_photo do
association :image, factory: :image
end

factory :image do
    photo { fixture_file_upload(Rails.root.join("spec", "fixtures", "pass.jpg"), "image/jpg") }
  end

当我使用“FactoryGirl.create(:menu_photo)”在rails控制台测试环境中测试时,它可以正常工作。它创建了:menu_photo和:image。 但是当我用“FactoryGirl.create(:food)”运行它时,它会出错: NoMethodError:#

的未定义方法`each'

1 个答案:

答案 0 :(得分:0)

我认为问题在于您正在尝试为has_many关联设置单个图像。如果你这样做会怎么样:

 factory :food do

    after(:create) { |f| 
       f.images.create!()
    }

 end
相关问题