用FactoryGirl建立假資料
安裝FactoryGirl
先在 Gemfile
內寫:
gem 'rspec-rails'
gem 'factory_girl_rails'
執行 bundle install
上面這種方式會順便把RSpec
給裝起來,反正沒壞處
接著打開 config/application.rb
加入
config.generators do |g|
g.test_framework :rspec, :fixture => true, :views => false, :fixture_replacement => :factory_girl
g.fixture_replacement :factory_girl, :dir => "spec/factories"
end
這樣做的話會在建立Model的時候一併建立相關檔案。
第一步
假設我們建立 Post
model
rails g model Post title:string content:string author:string state:string; rake db:migrate
現在可以開始建立測試資料了,打開 spec/factories/posts.rb
我們先新增一個正常的資料結構
FactoryGirl.define do
factory :post do
title "MyString"
content "MyString"
author "HeChien"
state "public"
end
end
這樣子,我們就可以在rails console
內透過FactoryGirl.create :post
來建立一筆Post資料了
怎麼了?你忘了?說好的,亂數呢?
誰跟你說好了=_= … 不過要亂數的話 …
假設我們要讓title
變亂數,那就把title
改為
title "MyString" # 原本是這樣
sequence(:title) { |n| "Title -- #{n}" } # 改成這樣
如此一來就會產生"Title -- 1"
、"Title -- 2"
之類的資料了
但是有的時候我們想要產生客製化的資料,譬如像是又亂數標題又是state
為closed
的文章的話要怎辦?
那就看下一節啊
第二步 - 不同狀態不同內容
同樣都是定義在Post
中,我們可能需要不一樣的狀態、內容,所以我們可以這樣做
# 1. title為亂數,content為亂數,發佈為published,author為亂數,叫做 :random_life
# 2. title為"Hello, world",content為"XD",發佈為closed,author為預設,叫做 :posted_by_hechien
# 改成以下這樣
FactoryGirl.define do
factory :post do
title "MyString"
content "MyString"
author "HeChien"
state "public"
factory :random_life do
sequence(:title) { |n| "Title -- #{n}" }
sequence(:content) { |n| "Randome #{n} Content" }
state "published"
sequence(:author) { |n| "Author: #{n}" }
end
factory :posted_by_hechien do
title "Hello, world"
content "XD"
state "closed"
end
end
end
如此一來,我們就可以用
FactoryGirl.create :random_life
來產生幾乎都亂數的資料,以及用 FactoryGirl.create :posted_by_hechien
來產生與我本人有關的資料XD
第三步 - Relationship :”>
臉紅個屁!
總是會需要建立關連的,譬如說Post
與Comment
。
FactoryGirl.define do
factory :comment do
post do
FactoryGirl.create :post
end
author "MyString"
content "MyString"
end
end
好了,你已經知道怎麼做了 (誤
與 db/seeds.rb
邂逅
100.times { FactoryGirl.create :random_life }
10.times { FactoryGirl.create :posted_by_hechien }
20.times { FactoryGirl.create :post }
rake db:seed
打完收工
但事實上,假資料要用這個建立 => https://github.com/ryanb/populator