ruby-on-rails - 将Elasticsearch与RSpec和Factorygirl一起使用

标签 ruby-on-rails elasticsearch rspec factory-bot

我找到了一篇很棒的文章,关于将Elasticsearch与RSpec here集成在一起,但是每当我使用Factorygirl创建模型时,似乎都不会添加到我的Elasticsearch索引中。关于如何使用Factorygirl向Elasticsearch添加模型的任何想法?

这是我的代码

display_controller_spec.rb:

    it "will return a list of displays", :elasticsearch do
      FactoryGirl.create(:display, client: @client)

      get :index, { :format => :json }, { "Accept" => "application/json" }
      # returns Status: 200 OK
      expect(response.status).to eq 200

      json = JSON.parse(response.body)
      expect(json.count).to be > 0
    end

display.rb:
    require 'elasticsearch/model'

    class Display < ActiveRecord::Base
      include Elasticsearch::Model
      include Elasticsearch::Model::Callbacks
      index_name ['company', Rails.env, self.base_class.to_s.pluralize.underscore].join('_')
...

factory / displays.rb
FactoryGirl.define do
  sequence(:display_name) {|n| "Display ##{n}"}

  factory :display do
    name { generate(:display_name) }
    client
  end
end

spec_helper.rb:
  config.before(:each) do
    [Event, Interaction, Perch].each do |model|
      model.__elasticsearch__.create_index!(force: true)
    end
  end

最佳答案

我有这个设置工作。我认为您只是缺少对Model.import的调用,以将记录导入elasticsearch中。您还需要确保任何工厂创建都可以进行!阻止,不在您的测试之内,以便导入将获取这些新记录。尝试这样的事情:

display_controller_spec.rb:

context "elasticsearch tests" do
  let!(:display) { FactoryGirl.create(:display, client: @client) }

  it "will return a list of displays", :elasticsearch do
    get :index, { :format => :json }, { "Accept" => "application/json" }
    # returns Status: 200 OK
    expect(response.status).to eq 200

    json = JSON.parse(response.body)
    expect(json.count).to be > 0
  end
end

spec_helper.rb:
RSpec.configure do |config|

  ...

  ES_CLASSES = [Event, Interaction, Perch]

  config.before :all do
    ES_CLASSES.each do |esc|
      esc.__elasticsearch__.client.indices.create(
        index: esc.index_name,
        body: { settings: esc.settings.to_hash, mappings: esc.mappings.to_hash }
      )
    end
  end

  config.after :all do
    ES_CLASSES.each do |esc|
      esc.__elasticsearch__.client.indices.delete index: esc.index_name
    end
  end

  config.before(:each, elasticsearch: true) do
    ES_CLASSES.each { |esc| esc.import(refresh: true, force: true) }
  end
end

关于ruby-on-rails - 将Elasticsearch与RSpec和Factorygirl一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33641207/

相关文章:

mysql - 如何使用 Arel 选择固定值?

html - 使用 actionmailer 时如何根据设备类型或屏幕大小调整图像大小?

ruby-on-rails - 在两个 Rails 服务器之间传输数据

ruby - 对记录的 Rspec stub 方法调用

ruby-on-rails - rspec rails 测试 : how can I force ActiveJob job's to run inline for certain tests?

javascript - 使用 haml 在 javascript 中打印 Ruby

java - 开玩笑按名称对结果进行排序

elasticsearch - Kibana中的查询不使用Regexp返回日志

mongodb - 使用 logstash 将 mongo 数据同步到弹性

ruby-on-rails - 如何将变量从 let 传递到共享示例?