ruby-on-rails - 工厂女孩 : How to set up a has_many/through association

标签 ruby-on-rails bdd factory-bot

我一直在努力设置 has_many/through使用工厂女孩的关系。

我有以下型号:

class Job < ActiveRecord::Base
  has_many :job_details, :dependent => :destroy
  has_many :details, :through => :job_details
end

class Detail < ActiveRecord::Base
  has_many :job_details, :dependent => :destroy
  has_many :jobs, :through => :job_details
end

class JobDetail < ActiveRecord::Base
  attr_accessible :job_id, :detail_id
  belongs_to :job
  belongs_to :detail
end

我的工厂:
factory :job do
  association     :tenant
  title           { Faker::Company.catch_phrase }
  company         { Faker::Company.name }
  company_url     { Faker::Internet.domain_name }
  purchaser_email { Faker::Internet.email }
  description     { Faker::Lorem.paragraphs(3) }
  how_to_apply    { Faker::Lorem.sentence }
  location        "New York, NY"
end

factory :detail do
  association :detail_type <--another Factory not show here
  description "Full Time"
end

factory :job_detail do
  association :job
  association :detail
end

我想要的是使用默认值创建我的工作工厂 Detail的“全职”。

我一直在努力遵循这一点,但没有任何运气:
FactoryGirl Has Many through

我不知道如何 after_create应该用于通过 JobDetail 附加 Detail。

最佳答案

尝试这样的事情。你想建一个detail对象并将其附加到作业的详细信息关联中。当您使用 after_create ,创建的作业将被交给区块。因此,您可以使用 FactoryGirl 创建详细信息对象,并将其直接添加到该作业的详细信息中。

factory :job do
  ...

  after_create do |job|
    job.details << FactoryGirl.create(:detail)
  end
end

关于ruby-on-rails - 工厂女孩 : How to set up a has_many/through association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444878/

相关文章:

ruby-on-rails - 将 factory_girl 与 PaperClip 4.0 结合使用

ruby-on-rails - 使用 Rspec、Devise 和 Factory Girl 测试用户模型

ruby-on-rails - 如何向现有的通知负载添加属性?

ruby-on-rails - 对并发请求使用 thin

java - 如何解决解析功能文件时出现错误的runtime.cucumberException

visual-studio-2010 - 在 VS2010 中执行 BDD 的标准方法是什么?

video - TDD/BDD 截屏/视频资源

ruby-on-rails - ActionCable:每个用户一个 channel

ruby-on-rails - 为什么结果是从数据库而不是缓存加载的?

ruby-on-rails - 带有 FactoryGirl 显式主题的 RSpec