简体   繁体   English

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

[英]Store test data from rails into database

I want to store my test data in database automatically when i run my application. 我想在运行应用程序时将测试数据自动存储在数据库中。

The following is the data that i want to use: 以下是我要使用的数据:

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');

I want to know where to add these lines?? 我想知道在哪里添加这些行? I don't want to run either rake db:migration/seed but i want when i start my application like start the server it should be included in the database. 我既不想运行rake db:migration/seed但我想在启动应用程序(如启动服务器)时将其包含在数据库中。 Any Idea??? 任何想法???

1) create a file in config/initializers/test_data.rb 1)在config/initializers/test_data.rb创建一个文件

2) In that file 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');") 

Is there any reason you can't use fixtures or factory_girl ? 有什么原因不能使用固定装置factory_girl吗?

To use fixtures, you would place a yaml file in spec/fixtures or test/fixtures named crm_donation_email_types.yml and the contents would be 要使用固定装置,您可以将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 will insert records according to this file when you run the unit test for this specific model. 当您为此特定模型运行单元测试时,Rails将根据该文件插入记录。 If you need these fixtures in other tests, then use the fixtures class method. 如果在其他测试中需要这些灯具,请使用fixtures类方法。 Read 2.3 The Low-Down on Fixtures for all the details. 阅读2.3灯具的所有细节。

If you decide to go with factory_girl, read the GETTING_STARTED guide. 如果您决定选择factory_girl ,请阅读GETTING_STARTED指南。

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

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