跳到主要內容

使用 RSpec 測試 model

在 model 中最基本的不外忽 table 之間的關聯,以及欄位的資料型別…等。
將使用 factory girl 以及 shoulda 這兩個 gem libs 協助建設測試資料,以及簡化程式。

在 Gemfile 加入下列:

--
gem 'factory_girl'
gem 'shoulda'
--

bundle install 安裝。

以 user model 為例,假設每個 user 都有自己的 profile,而關聯為 user belongs to profile。
每個 user 都有 username 以及 birthday,那麼 spec 中可以如下描述:

--
require 'spec_helper'

describe User do
  context "associations" do
    it { should belong_to(:profile).dependent(:destroy) }    -- (1)
  end

  context "database column and format" do
    it { should have_db_column(:username).of_type(:string) }   -- (2)
    it { should have_db_column(:birthday).of_type(:datetime) }   -- (3)
  end
end
--

(1) 測試 User model 與 profile 是否有 belongs to 的關聯
(2) 測試 table 'users' 是否有 username 的 column,資料型態為 string
(3) 測試 table 'users' 是否有 birthday 的 column,資料型態為 datetime

Model 的關聯以及欄位是最最基本的,其它更多的測試用法下回補上

Testing code 這種東西,總是在一開始時覺得不重要,容易忽略它⋯⋯
等到功能愈來愈多,schema 愈來愈複雜時,它的重要性和威力就展現了!


Reference:
https://gist.github.com/2353100
http://rubydoc.info/gems/thoughtbot-shoulda/2.11.1/frames
http://rubydoc.info/gems/factory_girl/1.3.3/frames

p.s: 一定要記取前輩的教訓,testing 能多早寫就多早寫,再簡單的功能都要測試!
即使只是一個 link,都要有 testing ⋯⋯

留言

這個網誌中的熱門文章

[lyrics] Imagine

Title: Imagine Artist: John Lennon Imagine there's no Heaven It's easy if you try No hell below us Above us only sky Imagine all the people Living for today Imagine there's no countries It isn't hard to do Nothing to kill or die for And no religion too Imagine all the people Living life in peace You may say that I'm a dreamer But I'm not the only one I hope someday you'll join us And the world will be as one Imagine no possessions I wonder if you can No need for greed or hunger A brotherhood of man Imagine all the people Sharing all the world You may say that I'm a dreamer But I'm not the only one I hope someday you'll join us And the world will live as one ----------------------------- 這首歌和歌詞是早就知道的,最近又再次聽起它並認真的讀了歌詞 真的,很感動,多麼美好的世界~ (遠目) 真的也無法形容浮現在腦中的畫面.... 只能用心來感受它吧! 同樣的東西在不同的時間下會有新的,全然不同的感受.... 也有許多事情,是要親自走過、痛過、經歷過,才能了解那份感受 寫這個沒什麼意義,只是紀錄當下的感覺罷了!

白揚瀑布

 

健保卡代號

IC卡載入後,欄位代碼之表示為: *(1)代表「同意器官捐贈,不同意安寧緩和醫療」 *(4)代表「同意器官捐贈,同意安寧緩和醫療,同意不 施行心肺復甦術」 *(7)代表「不同意器官捐贈,同意安寧緩和醫療,同意 不施行心肺復甦術」 *未註記 p.s: 今天看牙醫順便請醫生幫我看一下,醫生說是代號(4),簽成功了 :) ref: http://www.tho.org.tw/xms/read_attach.php?id=259