簡體   English   中英

如何通過測試數據庫加載Rails測試環境?

[英]How do you load Rails test environment with test db?

我想為Rails加載測試環境以運行我的最小測試。

將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'

有時測試數據庫可能不同步。 我不太確定是什么原因引起的...但是我通常可以通過在測試環境下運行數據庫相關的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' require "test_helper" require_relative '../test_helper.rb'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM