maeshimaの日記

メモ書きです

sunspot-rails-tester

justinko/sunspot-rails-tester - GitHubのREADMEの意訳。

この gem は特定の箇所のテストで solr をオンにするためのもの。solr を使用せず、sunspot を stub 化することで不必要なインデックス構築を避けている。

RSpec2 の spec_helper.rb の例。

$original_sunspot_session = Sunspot.session

RSpec.configure do |config|
  config.mock_with :rspec

  config.before do
    Sunspot.session = Sunspot::Rails::StubSessionProxy.new($original_sunspot_session)
  end

  config.before :solr => true do
    Sunspot::Rails::Tester.start_original_sunspot_session
    Sunspot.session = $original_sunspot_session
    Sunspot.remove_all!
  end
end
  • $original_sunspot_session はオリジナルの sunspot セッションを格納する。デフォルトで、 sunspot_rails は SessionProxy::ThreadLocalSessionProxy を使う。
  • 最初の before ブロックでは、 stub セッションを全ての example 用にセットしている。 Sunspot::Rails::StubSessionProxy はインデックス作成をスキップさせるダミークラス。
  • 二つ目の before ブロックは、:solr => true とすることで RSpec2 のメタデータ機能を使っている。:solr => true とした example または example group ではオリジナルの sunspot session を使う。Sunspot::Rails::tester.start_original_sunspot_session はもし solr のインスタンスが動いてなかったら動かす。

sunspot-rails-tester を使った例

require 'spec_helper'

describe 'search page' do
  it 'highlights the active tab in the navigation' do
    # uses the stub session
  end

  it 'finds and displays a person', :solr => true do
    # uses actual solr - indexing will happen
  end
end