黃金俠

Ruby on Rails / Rubygems / Javascript / Git

factory_girl 中的 model 關連 (association)

| Comments

不論是 one-to-one one-to-manymany-to-many, 我們都希望 model 中的關連也能反應到 factory_girl 的定義中

方法如下: (brand has many products)

spec/factories/brands.rb
1
2
3
4
5
FactoryGirl.define do
  factory :brand do
    sequence(:name) { |n| "brand name #{n}" }
  end
end
spec/factories/products.rb
1
2
3
4
5
6
7
8
FactoryGirl.define do
  factory :products do
    name "product name"
    brand do
      Factory :brand
    end
  end
end
app/models/product.rb
1
2
3
class Product < ActiveRecord::Base
  belongs_to :brand  # brand_id
end

如此只要每次 Factory(:product) , 該 product 的 brancd 也會透過 brancd 產生, 而不需要再每次的 factory 中去進行關連了 Factory(:product, :brand => Factory(:brand))

Comments