我想为Rails加载测试环境以运行我的最小测试。
我需要配置/环境。
将RAILS_ENV设置为'test'。似乎这不是正确的方法,因为测试数据库似乎没有被创建。
我知道这是一个相当奇怪的问题,但我没有看到其他人真的问过这个问题。
*Code in my test/test_helper.rb
require 'minitest/autorun'
ENV['RAILS_ENV'] = 'test'
require_relative '../config/environment'
*在Test/models/users_test.rb中的Basic Boiler Plate和Sanity Test
require_relative '../test_helper.rb'
class UserModelTest < MiniTest::Test
def setup
@user = User.new
@user.email = 'me@example.com'
@user.password = 'password'
@user.save
end
def test_sanity
assert true
end
end
*我从上面的setup方法中得到的错误使我认为测试数据库没有被创建和迁移
Error:
UserModelTest#test_sanity:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "users" does not exist
LINE 5: WHERE a.attrelid = '"users"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"users"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
/home/john/.rvm/gems/ruby-2.1.1@mangam/gems/activerecord-4.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:815:in `async_exec'
.
.
.
/home/john/.rvm/gems/ruby-2.1.1@mangam/gems/activerecord-4.1.0/lib/active_record/inheritance.rb:23:in `new'
test/models/users_test.rb:6:in `setup'
有时测试数据库可能不同步。我不太确定是什么原因造成的……但是我通常可以通过在测试环境下运行与数据库相关的rake命令来解决这个问题。在您的情况下,看起来迁移只是不同步,所以请尝试:
RAILS_ENV=test bundle exec rake db:migrate
此外,在Rails 4.1中,这是默认的test_helper。Rb 文件看起来应该是这样的,所以你可能需要调整你的:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
那么在您的测试文件中,您可以只使用require "test_helper"
而不是require_relative '../test_helper.rb'
。