【问题标题】:How do you load Rails test environment with test db?如何使用测试数据库加载 Rails 测试环境?
【发布时间】:2014-08-25 10:58:40
【问题描述】:

我想为 Rails 加载测试环境来运行我的 minitest 测试。

在将 RAILS_ENV 设置为“测试”后,我需要 config/environment.rb。

这似乎不是正确的方法,因为似乎没有创建测试数据库。

我知道这是一个非常愚蠢的问题,但我没有看到其他人真正问过这个问题。

*我的 test/test_helper.rb 中的代码

require 'minitest/autorun'

ENV['RAILS_ENV'] = 'test'

require_relative '../config/environment'

*test/models/users_test.rb 中的基本锅炉板和健全性测试

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

*我从上面的设置方法中得到的错误让我认为测试数据库没有被创建和迁移

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'

【问题讨论】:

    标签: ruby-on-rails ruby minitest


    【解决方案1】:

    有时测试数据库可能会不同步。我不太确定是什么原因造成的……但我通常可以通过在测试环境下运行与数据库相关的 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'

    【讨论】:

    • 感谢您的回答。我想我会在 test_helper 中删除、创建和迁移测试数据库。不过,我不确定是否使用 ActiveSupport 进行测试。这样做有真正的好处吗?我想我会保持简单,所以只使用 minitest 断言应该没问题。再次感谢
    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2018-03-05
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多