我正在尝试使用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 < C:\\Brian\\Work\\Personal\\BrianSite\\database\\Fill_Test_Tables.sql"
puts "Starting rails test environment..."
task :run => :environment do
puts "RAILS_ENV is #{RAILS_ENV}"
require "spec/models/blog_spec.rb"
end
end
我认为要求“spec / models / blog_spec.rb”文件会这样做,但它似乎没有运行测试......
感谢您的帮助。
答案 0 :(得分:33)
这个命令为我做了。我能够用它的数据库加载测试env aloong。
$rails s -e test
答案 1 :(得分:9)
要启动测试环境,您应该使用-e
param运行脚本/服务器:
ruby script/server -e test
并且你的config / database.yml必须是测试env数据库的定义,即:
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
答案 2 :(得分:6)
你知道你可以从Rake运行你的单元,功能和集成测试,对吧?查看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