加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Railstutorial:db:populate vs. factory gir

发布时间:2020-12-17 03:34:51 所属栏目:百科 来源:网络整理
导读:在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'].i
在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 => "example@railstutorial.org",: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                 "mhartl@example.com"
  user.password              "foobar"
  user.password_confirmation "foobar"
end

似乎两种方式都在数据库中创建用户权限(工厂女孩是否在数据库中创建用户)?创建测试用户的两种不同方式是什么原因,它们有何不同?什么时候一种方法比另一种方法更合适?

解决方法

Faker和Factory Girl正在这些例子中用于两个不同的目的.

使用Faker创建rake任务,可以轻松地填充数据库,通常是开发数据库.这使您可以使用大量填充的假数据浏览应用程序.

工厂定义使测试更方便.例如,在您的RSpec测试中,您可以编写:

before(:each) do
 @user = Factory(:user)
end

然后@user在随后的测试中可用.它会将这些更改写入测试数据库,但请记住,每次运行测试时都会清除这些更改.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读