天天看點

fixtures --- 建構關系表資料

在寫測試時很多時候我們都會利用fixtures構造資料,特别在構造關系表的資料時就顯得特别麻煩。

我在看railscast 看到一種比較簡單的方法,不用構造關系表,覺得有用,特别記錄下來,便于以後查找:

#####  /models/products.rb

class Product < ActiveRecord::Base

belongs_to :user

has_and_belongs_to_many :categories

end 

##### /spec/fixtures/users.yml

lilei:

id: 1

name: lilei

hanmeimei:

id: 2

name: hanmeimei 

##### /spec/fixtures/categories.yml

furnitur:

id: 1

name: Furniture

electronics:

id: 2

name: Electronics 

##### /spec/fixtures/products.yml

couch:

id: 1

name: couch

price: 199.00

user: lilei #不再使用 user_id: 1

categories: furniture

computer:

id: 2

name: computer

price: 366.00

user: hanmeimei #不再使用 user_id: 2

categories: furniture,electronics 

用了categories 就直接省去了建立products_categories 這個中間表的資料:

##### /spec/fixtures/products_categories.yml

couch_furniture:

product_id: 1

category_id: 1

computer_furniture:

product_id: 2

category_id: 1

computer_electronics:

product_id: 2

category_id: 2 

繼續閱讀