もう1つの方法として、sqlite3アダプタを使用してデータベースをメモリ上で実行し、DatabaseCleanerを使用してテスト後のレコードを削除します。
このアプローチにはいくつかの利点があります、あなたがテストにSQLを見ることができます
- クエリ最適化プロセス
- を簡素化することは、「現実の生活」の例で
に近いですもう少し時間がかかりますが、それを再構成しても構わないと思います)
ここでは簡単な説明が必要ですRそれは:私は事を保つために、次のアプローチを使用していますが、あなたは歓迎されている
# in Gemfile
gem "activerecord" #since you are dealing with activerecord
gem "database_cleaner", :group => :test
gem "sqlite3", :group => :test
異なり、それを持っている:
# in RAILS_ROOT/test/support/active_record.rb
require 'logger'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3", :database => ':memory:'
)
#this line will print the SQL queries right into console
ActiveRecord::Base.logger = Logger.new(STDOUT)
# in RAILS_ROOT/test/support/database_cleaner.rb
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
# or DatabaseCleaner.strategy = :trunsaction (it is up to you)
module OrmSetup
def before_setup
DatabaseCleaner.start
end
def after_teardown
DatabaseCleaner.clean
end
end
# in RAILS_ROOT/test/test_helper.rb
...
require File.expand_path("support/active_record", File.dirname(__FILE__))
require File.expand_path("support/database_cleaner", File.dirname(__FILE__))
class Test::Unit::TestCase
include OrmSetup
end
そして今、あなたのテストであなたが持つことができる何かを
のように
require 'test_helper'
class User < ActiveRecord::Base
end
class MyFancyTest < Test::Unit::TestCase
def setup
before_setup
end
def teardown
after_teardown
end
end
出典
2012-09-20 17:01:23
Max
これはまさに私が探していたものです。ありがとう! –
このライブラリの欠点は、Rspecにどのように結合されているかです。あなたがRspec –
+1を使っていない場合、私の側から覚えておくべきこと... –