我发现了一篇关于将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('_')
...
工厂/ 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
答案 0 :(得分:1)
我有这个设置工作。我想你只是错过了对Model.import的调用,将记录导入到elasticsearch中。您还需要确保任何工厂创建发生在let!阻止,不在您的测试范围内,以便导入将获取这些新记录。尝试这样的事情:
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