Rails Tutorial : Add testing data by using migration

by toy

From previous tutorial Rails Tutorial : Beer shop Part I – Scaffolding I have show how to create a very simple scaffolding. This tutorial I will show how to create a testing data. Nobody wants to type SQL statement or add item manually every time they want to use the data. Rails has provided a handy tool to support this already.

1. add testing data

2. This will create a file in migrate folder ready to use

1
2
3
4
5
6
7
class AddTestData < ActiveRecord::Migration
  def self.up
  end

  def self.down
  end
end

3. We now add test data by editing file add_test_data.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class AddTestData < ActiveRecord::Migration
  def self.up
    Beer.delete_all
    Beer.create(:name => "Artvelde",
      :abv => "5.4%",
      :bottle_size => 250,
      :case_size => 24,
      :price => 30.03)

    Beer.create(:name => "Biere Du Boucanier Dark Ale",
      :abv => "9%",
      :bottle_size => 330,
      :case_size => 24,
      :price => 55.64)

    Beer.create(:name => "Bush Ambree",
      :abv => "12%",
      :bottle_size => 250,
      :case_size => 24,
      :price => 50.98)

    Beer.create(:name => "Cantillon Grand Cru Bruocsella",
      :abv => "5%",
      :bottle_size => 750,
      :case_size => 6,
      :price => 46.5)
  end

  def self.down
    Beer.delete_all
  end
end