ruby-on-rails - Factory Girl 多态 has_many, belongs_to

标签 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

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

的未定义方法“each”

最佳答案

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

 factory :food do

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

 end

关于ruby-on-rails - Factory Girl 多态 has_many, belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13225255/

相关文章:

ruby-on-rails - 将数组的数组拆分,[0] 拆分为一个,[1] 拆分为另一个

ruby-on-rails - 服务器重启后 Passenger 启动 Rails 应用

php - Laravel 5 如何以正确的方式在不同的数据库中运行测试?

ruby-on-rails - Rspec:验证失败:名称已被占用

mysql - 持续扩展更多表的数据库的最佳实践

ruby-on-rails - Rspec/Rails 中的 stub 模型保存方法

css - 如何模拟像素比以在 Windows 上使用 Google Chrome 或 Firefox 测试媒体查询?

python - 测试发布请求时 Django 消息中间件问题

ruby-on-rails-3 - Rails 3 工厂女孩 + 多对多关系

activerecord - FactoryGirl 协会 Parent 不能为空