學習札記——Rspec+factory_girl進行復雜模型測試

本文主要介紹怎麼使用Rspec+factory_girl進行復雜模型測試,

首先介紹下本人使用的模型機構
class Node
belongs_to :parent,:class_name =>Node
has_many :children,:class_name =>Node
                :foreign_key =>:parent_id
end

end
可以看出,我使用的是一個自關聯表,通過自己:parent_id這個鍵將本表自己關聯起來,
現在介紹怎麼用factory_girl模擬這樣的模擬結構
首先介紹從葉子結點像root結點一個一對一的模型結構
代碼如下
FactoryGirl.define do
factory :node do
title "XXXXX"
factory :node_leaf ,:class => :node do
association :parent,:factory =>:node
end
end

通過association這個值,我們將node與node_leaf做成一對一關聯
然後我們再構建root結點向leaf結點一個一對多的情況
FactoryGirl.define do
factory :node do
title "XXXXX"
factory :node_root,:class => :node do
after_create do |node|
node.children <<FactoryGirl.create(:node,:parent => node)
node.children <<FactoryGirl.create(:node,:parent => node)
node.children <<FactoryGirl.create(:node,:parent => node)
end
end
end
end
然後我們再下Rspec代碼中創建測試模型
Factory.build(:node_root) #這種方式不會被保存在數據庫中
Factory.create(:node_leaf)#這種方式其實就多了一個SAVE動作
如果想查找可以下一結點用關鍵字查詢比如
Factory.create(:node_root).children.find_by_title("1")

也可以使用:each這個選項遍歷整個模型比如
Factory.create(:node_root).children.each do |node|
node.title
end

參考資料
https://github.com/thoughtbot/factory_girl/issues/202關於一對多的關係
http://www.cnblogs.com/ToDoToTry/archive/2011/09/10/2173382.htmlfactory_girl 測試
http://ruby-china.org/topics/3777很不錯關於factory_girl的介紹,很全面


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章