将Elasticsearch集成到RSpec的功能规范中

在使用Rails/RSpec编写测试时,因为需要编写使用Elasticsearch进行搜索的测试,所以在此做个备忘录。

运动环境:

    • Ruby: 2.1.2p95

 

    • Rails: 4.0.5

 

    • RSpec: 3.0.4

 

    Elasticsearch: Version: 1.1.1

1) 宝石增加

如果没有这些宝石,似乎根本不可能。

gem 'elasticsearch-rails'
gem 'elasticsearch-extensions'

将与Elasticsearch的处理添加到spec_helper.rb中。

    • Elasticsearchは(確か)デフォルトで9200のポートを使うので、テストでは別のポートを割り当ててテスト用のElasticsearchサーバを立てるようにする。

 

    毎回Elasticsearchサーバが立ち上がるととても重たいので、elasticsearch: trueのメタタグをつけたブロックのみで有効になるようにしている

/spec/spec_helper.rb可以这样翻译成中文:

/spec/spec_helper.rb规范说明如下:

require 'elasticsearch/extensions/test/cluster'

Elasticsearch::Model.client = Elasticsearch::Client.new(host: "localhost:9250")

# other configs

# elasticsearch config
config.before(:each, elasticsearch: true) do
  unless Elasticsearch::Extensions::Test::Cluster.running?(on: 9250)
    Elasticsearch::Extensions::Test::Cluster.start port: 9250, nodes: 1
  end
  User.__elasticsearch__.create_index! force: true
  User.__elasticsearch__.refresh_index!
end
at_exit do
  if Elasticsearch::Extensions::Test::Cluster.running?(on: 9250)
    Elasticsearch::Extensions::Test::Cluster.stop port: 9250
  end
end

3) 在模型规格中添加搜索测试。

    • あらかじめモデルのほうにはElasticsearchを使った検索時に:nameカラムがひっかかるようにしておく

 

    以下のように、Userモデルでは:nameカラムでの検索が有効になることをテストする

以下是/user_spec.rb的模型测试文件。

let(:user) { create(:user) }

describe ':search_matching_user', elasticsearch: true do
  before do
    user.__elasticsearch__.index_document
    Elasticsearch::Model.client.indices.flush
  end

  context 'nameで検索できる' do
    let(:user) { create(:user, name: "John Doe") }
    subject { User.search_match_customer_organizations("John").records.to_a }

    it { is_expected.to eq [user] }
  end
end

差不多这样。

通过这种方式,我们可以编写包含使用Elasticsearch的搜索功能的特性测试。
由于在运行带有Elasticseach的测试时,每次都要启动测试用的Elasticsearch服务器,所以执行会花费一些时间。如果经常使用这种方式,测试将会变得很慢。

it 'ユーザを登録してそのユーザを検索する', js: true, elasticsearch: true do
  visit new_user_path
  fill_in 'user_name', with: 'Foo Bar'
  fill_in 'user_email', with: 'foo@bar.com'
  click_button 'Submit'

  expect(page).to have_content('Foo Bar')
  expect(page).to have_content('foo@bar.com')

  fill_in 'input_search', with: 'Foo'
  find_button('Search').click

  expect(find(".user_name")).to have_content('Foo Bar')
  expect(find(".user_emai")).to have_content('foo@bar.com')
end

顺便问一下

在Repro株式会社,我们正在寻找能够一起相互激励和成长的伙伴。请务必查看这里!

bannerAds