在 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 ⋯⋯
將使用 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 ⋯⋯
留言
張貼留言