繁体   English   中英

将测试数据从Rails存储到数据库中

[英]Store test data from rails into database

我想在运行应用程序时将测试数据自动存储在数据库中。

以下是我要使用的数据:

INSERT INTO `crm_donation_email_types` (`id`, `emailtype`, `created_at`, `updated_at`) VALUES
(1, 'to', '2013-08-28 05:19:08', '2013-08-28 05:19:08'),
(2, 'cc', '2013-08-28 05:19:15', '2013-08-28 05:19:15'),
(3, 'bcc', '2013-08-28 05:19:26', '2013-08-28 05:19:26'),
(4, 'from', '2013-08-28 05:19:35', '2013-08-28 05:19:35');

我想知道在哪里添加这些行? 我既不想运行rake db:migration/seed但我想在启动应用程序(如启动服务器)时将其包含在数据库中。 任何想法???

1)在config/initializers/test_data.rb创建一个文件

2)在那个文件中

  conn = ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "myuser", :password => "mypass", :database => "test_database" )

  conn.execute("INSERT INTO 'crm_donation_email_types' ('id', 'emailtype', 'created_at', 'updated_at') VALUES   (1, 'to', '2013-08-28 05:19:08', '2013-08-28 05:19:08'), (2, 'cc', '2013-08-28 05:19:15', '2013-08-28 05:19:15'), (3, 'bcc', '2013-08-28 05:19:26', '2013-08-28 05:19:26'), (4, 'from', '2013-08-28 05:19:35', '2013-08-28 05:19:35');") 

有什么原因不能使用固定装置factory_girl吗?

要使用固定装置,您可以将yaml文件放置在spec/fixturestest/fixtures名称为crm_donation_email_types.yml ,其内容为

to:
  id: 1
  email_type: to
  updated_at: <%= DateTime.parse '2013-08-28 05:19:08' %>
  created_at: <%= DateTime.parse '2013-08-28 05:19:08' %>

cc:
  id: 2
  email_type: cc
  updated_at: <%= DateTime.parse '2013-08-28 05:19:15' %>
  created_at: <%= Datetime.parse '2013-08-28 05:19:15' %>

bcc:
  id: 3
  email_type: bcc
  updated_at: <%= DateTime.parse '2013-08-28 05:19:26'
  created_at: <%= DateTime.parse '2013-08-28 05:19:26'

from:
  id: 4
  email_type: from
  updated_at: <%= '2013-08-28 05:19:35' %>
  created_at: <%= '2013-08-28 05:19:35' %>

当您为此特定模型运行单元测试时,Rails将根据该文件插入记录。 如果在其他测试中需要这些灯具,请使用fixtures类方法。 阅读2.3灯具的所有细节。

如果您决定选择factory_girl ,请阅读GETTING_STARTED指南。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM