Railstutorial:db:populate 与工厂女孩
在railstutorial中,作者为什么选择使用这个(清单10.25): http://ruby.railstutorial.org/chapters/updating-showing-and -deleting-users
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
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}@railstutorial.org"
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end
用假用户填充数据库,并且(清单 7.16) http://ruby.railstutorial.org/chapters/modeling-and-viewing -users-two
Factory.define :user do |user|
user.name "Michael Hartl"
user.email "[email protected]"
user.password "foobar"
user.password_confirmation "foobar"
end
看来两种方式都在数据库中创建了用户(工厂女孩是否在数据库中创建了用户)?创建测试用户的两种不同方式的原因是什么?它们有何不同?什么时候一种方法比另一种方法更合适?
In the railstutorial, why does the author choose to use this (Listing 10.25):
http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
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}@railstutorial.org"
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end
to populate the database with fake users, and also (Listing 7.16)
http://ruby.railstutorial.org/chapters/modeling-and-viewing-users-two
Factory.define :user do |user|
user.name "Michael Hartl"
user.email "[email protected]"
user.password "foobar"
user.password_confirmation "foobar"
end
It appears that both ways creates users in the database right (does factory girl create users in the database)? What is the reason for the two different ways of creating test users, and how are they different? When is one method more suitable than the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些示例中使用 Faker 和 Factory Girl 的目的有两个不同的目的。
rake 任务是使用 Faker 创建的,可以轻松地填充数据库,通常是开发数据库。这使您可以浏览包含大量填充的虚假数据的应用程序。
工厂定义使得测试编写起来很方便。例如,在 RSpec 测试中,您可以编写:
然后 @user 在接下来的测试中可用。它将把这些更改写入测试数据库,但请记住,每次运行测试时这些更改都会被清除。
Faker and Factory Girl are being used in those examples for two different purposes.
A rake task is created using Faker to easily let you populate a database, typically the development database. This lets you browse around your app with lots of populated, fake data.
The factory definition makes tests convenient to write. For example, in your RSpec tests you can write:
Then @user is available in the tests that follow. It will write these changes to the test database, but remember that these are cleared each time you run tests.