faker 生成测试数据

 

在Gemfile中添加faker

gem 'faker', '1.0.1'

执行bundle install

 

在lib/tasks下创建sample_data.rake文件,内容如下:

 

namespace :db do 
  desc "Fill database with sample data"
  task populate: :environment do
    #create和create!的区别是,create!发生错误的时候抛出异常,而create则返回false
    User.create!(name: "Example User",
                 email: "[email protected]",
		 password: "foobar",
		 password_confirmation: "foobar")
     99.times do |n|
       name = Faker::Name.name
       email = "example-#{n-1}@163.com"
       password = "password"
       User.create!(name: name,
                    email: email,
		    password: password,
		    password_confirmation: password)
     end
  end
end

 

rake -T 查看rake任务,就可以看到 rake db:populate  “Fill database with sample data”了

执行rake db:reset重置数据库

rake db:populate 在development模式下生成测试数据

 

 

 

 

 

你可能感兴趣的:(测试数据,faker)