本章介紹兩種最常用來建立測試資料的方法:
it "can tell which user is older" do
eldest = User.create(date_of_birth: '1971-01-22')
youngest = User.create(date_of_birth: '1973-08-31')
expect(User.find_eldest).to eq(eldest)
expect(User.find_youngest).to eq(youngest)
end
隨著時間的演進,我們加了authentication的功能到user model中,這時所有用到User.create的地方都必須加上email與password才可以被塞進資料庫。
it "can tell which user is older" do
eldest = User.create!(date_of_birth: '1971-01-22',
email: "eldest@example.com", password: "password")
youngest = User.create!(date_of_birth: '1973-08-31',
email: "youngest@example.com", password: "password")
expect(User.find_eldest).to eq(eldest)
expect(User.find_youngest).to eq(youngest)
end
隨著時間的演進,我們又加了height, zip code與handedness(慣用手)的validation…
it "can tell which user is older" do
eldest = User.create!(date_of_birth: '1971-01-22',
email: "eldest@example.com", password: "password",
height: 185, zip code: "60642", handedness: "left")
youngest = User.create!(date_of_birth: '1973-08-31',
email: "youngest@example.com", password: "password",
height: 178, zip code: "60642", handedness: "ambidextrous")
expect(User.find_eldest).to eq(eldest)
expect(User.find_youngest).to eq(youngest)
end
由上面的例子可以發現,一旦user model的validation做變動,所有用到user create的測試都要做變動,這是件非常可怕的事。
請參考:使用factory來建立測試資料
請參考:如何測試時間