在测试环境中启动轨道

我正在尝试使用ruby脚本在测试环境中加载rails。 我尝试了谷歌搜索,发现这个建议:

require "../../config/environment" ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'test' 

这似乎加载了我的环境,但我的开发数据库仍在使用中。 难道我做错了什么?

这是我的database.yml文件…但我不认为这是问题

 development: adapter: mysql encoding: utf8 reconnect: false database: BrianSite_development pool: 5 username: root password: dev host: localhost # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: mysql encoding: utf8 reconnect: false database: BrianSite_test pool: 5 username: root password: dev host: localhost production: adapter: mysql encoding: utf8 reconnect: false database: BrianSite_production pool: 5 username: root password: dev host: localhost 

我不能用

 ruby script/server -e test 

因为我在加载rails后尝试运行ruby代码。 更具体地说,我要做的是:运行.sql数据库脚本,加载rails,然后运行自动化测试。 一切似乎都运行良好,但无论出于何种原因,rails似乎在开发环境而不是测试环境中加载。

这是我试图运行的代码的缩短版本:

 system "execute mysql script here" require "../../config/environment" ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'test' describe Blog do it "should be initialized successfully" do blog = Blog.new end end 

我不需要启动服务器,我只需要加载我的rails代码库(模型,控制器等),这样我就可以对我的代码运行测试。

谢谢你的帮助。

更新:

我现在正在加载我的rails环境。 现在我正在尝试在我的rake任务中运行我的测试文件。 这是我的代码:

 require"spec" require "spec/rake/spectask" RAILS_ENV = 'test' namespace :run_all_tests do desc "Run all of your tests" puts "Reseting test database..." system "mysql --user=root --password=dev < C:\\Brian\\Work\\Personal\\BrianSite\\database\\BrianSite_test_CreateScript.sql" puts "Filling database tables with test data..." system "mysql --user=root --password=dev  :environment do puts "RAILS_ENV is #{RAILS_ENV}" require "spec/models/blog_spec.rb" end end 

我认为要求“spec / models / blog_spec.rb”文件会这样做,但它似乎没有运行测试…

感谢您的帮助。

你知道你可以从Rake运行你的单元,function和集成测试,对吗? 检查rake -T test的输出,看看如何。

如果您需要更多自定义内容,您可以创建自己的Rake任务。 把这样的东西放在lib/tasks文件中:

 namespace :custom_tests do desc "Run my custom tests" task :run => :environment do puts "RAILS_ENV is #{RAILS_ENV}" system "execute mysql script here" # Do whatever you need to do end end 

=> :environment环境为您加载当前环境。 然后,您可以在测试环境中运行您的任务,如下所示: RAILS_ENV=test rake custom_tests:run

这个命令为我做了。 我能够用它的数据库加载测试env aloong。

 $rails s -e test 

要启动测试环境,您应该使用-e param运行脚本/服务器:

 ruby script/server -e test 

并且在你的config / database.yml中必须是测试env数据库的defenition,即:

 test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000