Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add Meilisearch search provider with integration tests
Damian Legawiec0b743e54fc8e
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 6f80a1a168..32654ea87d 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -135,11 +135,21 @@ jobs:--health-interval 10s--health-timeout 5s--health-retries 5+ meilisearch:+ image: getmeili/meilisearch:latest+ ports:+ - 7700:7700+ options: >-+ --health-cmd "curl -f http://localhost:7700/health"+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5env:DB: postgresDB_HOST: localhostDB_USERNAME: postgresDB_PASSWORD: postgres+ MEILISEARCH_URL: http://localhost:7700RAILS_VERSION: "~> 8.1.0"CI_ARTIFACTS: /tmp/test-artifactsBUNDLE_JOBS: 4diff --git a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rbnew file mode 100644index 0000000000..eefeed469d--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb@@ -0,0 +1,239 @@+require 'spec_helper'+require 'meilisearch'++# Integration tests that run against a real Meilisearch instance.+# Requires MEILISEARCH_URL to be set (e.g. http://localhost:7700).+# In CI, Meilisearch runs as a service container.+# Locally: `brew install meilisearch && meilisearch`+#+# Run with: bundle exec rspec spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb+RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARCH_URL'].present? do+ controller(Spree::Api::V3::Store::ProductsController) {}++ include_context 'API v3 Store'++ before(:all) { WebMock.allow_net_connect!(allow_localhost: true) }+ after(:all) { WebMock.disable_net_connect! }++ let(:provider) { Spree::SearchProvider::Meilisearch.new(store) }+ let(:index_name) { "#{store.code}_products" }++ # Categories+ let(:taxonomy) { create(:taxonomy, store: store) }+ let(:clothing_category) { create(:taxon, name: 'Clothing', taxonomy: taxonomy) }+ let(:shoes_category) { create(:taxon, name: 'Shoes', taxonomy: taxonomy) }++ # Option types+ let(:color_option) { create(:option_type, name: 'color', presentation: 'Color', filterable: true) }+ let(:size_option) { create(:option_type, name: 'size', presentation: 'Size', filterable: true) }+ let(:red) { create(:option_value, option_type: color_option, name: 'red', presentation: 'Red') }+ let(:blue) { create(:option_value, option_type: color_option, name: 'blue', presentation: 'Blue') }+ let(:small) { create(:option_value, option_type: size_option, name: 'small', presentation: 'S') }+ let(:large) { create(:option_value, option_type: size_option, name: 'large', presentation: 'L') }++ # Products with different attributes+ let!(:cheap_red_shirt) do+ p = create(:product, name: 'Red Cotton Shirt', status: 'active', stores: [store], taxons: [clothing_category])+ p.option_types << color_option+ p.option_types << size_option+ v = create(:variant, product: p, option_values: [red, small])+ v.prices.find_or_create_by!(currency: 'USD').update!(amount: 19.99)+ p+ end++ let!(:expensive_blue_shirt) do+ p = create(:product, name: 'Blue Silk Shirt', status: 'active', stores: [store], taxons: [clothing_category])+ p.option_types << color_option+ v = create(:variant, product: p, option_values: [blue, large])+ v.prices.find_or_create_by!(currency: 'USD').update!(amount: 89.99)+ p+ end++ let!(:blue_shoes) do+ p = create(:product, name: 'Blue Running Shoes', status: 'active', stores: [store], taxons: [shoes_category])+ p.option_types << color_option+ p.option_types << size_option+ v = create(:variant, product: p, option_values: [blue, small])+ v.prices.find_or_create_by!(currency: 'USD').update!(amount: 129.99)+ p+ end++ let!(:draft_product) { create(:product, name: 'Draft Hat', status: 'draft', stores: [store]) }++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ allow(Spree).to receive(:search_provider).and_return('Spree::SearchProvider::Meilisearch')++ provider.reindex(store.products)+ wait_for_meilisearch_indexing!+ end++ after do+ client = ::Meilisearch::Client.new(ENV['MEILISEARCH_URL'])+ client.delete_index(index_name) rescue nil+ allow(Spree).to receive(:search_provider).and_call_original+ end++ describe 'text search' do+ it 'finds products by name' do+ get :index, params: { q: { search: 'shirt' } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Red Cotton Shirt', 'Blue Silk Shirt')+ expect(names).not_to include('Blue Running Shoes')+ end++ it 'finds products with typo tolerance' do+ get :index, params: { q: { search: 'shrit' } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Red Cotton Shirt')+ end++ it 'finds products by partial match' do+ get :index, params: { q: { search: 'blue' } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Blue Silk Shirt', 'Blue Running Shoes')+ expect(names).not_to include('Red Cotton Shirt')+ end+ end++ describe 'filtering by price' do+ it 'filters by minimum price' do+ get :index, params: { q: { price_gte: '50' } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Blue Silk Shirt', 'Blue Running Shoes')+ expect(names).not_to include('Red Cotton Shirt')+ end++ it 'filters by maximum price' do+ get :index, params: { q: { price_lte: '50' } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Red Cotton Shirt')+ expect(names).not_to include('Blue Silk Shirt', 'Blue Running Shoes')+ end++ it 'filters by price range' do+ get :index, params: { q: { price_gte: '50', price_lte: '100' } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Blue Silk Shirt')+ expect(names).not_to include('Red Cotton Shirt', 'Blue Running Shoes')+ end+ end++ describe 'filtering by category' do+ it 'filters by category ID' do+ get :index, params: { q: { categories_id_eq: clothing_category.prefixed_id } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Red Cotton Shirt', 'Blue Silk Shirt')+ expect(names).not_to include('Blue Running Shoes')+ end+ end++ describe 'filtering by option values' do+ it 'filters by color option value' do+ get :index, params: { q: { with_option_value_ids: [blue.prefixed_id] } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Blue Silk Shirt', 'Blue Running Shoes')+ expect(names).not_to include('Red Cotton Shirt')+ end++ it 'filters by size option value' do+ get :index, params: { q: { with_option_value_ids: [small.prefixed_id] } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Red Cotton Shirt', 'Blue Running Shoes')+ expect(names).not_to include('Blue Silk Shirt')+ end+ end++ describe 'combined search + filters' do+ it 'searches text and filters by price' do+ get :index, params: { q: { search: 'blue', price_lte: '100' } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Blue Silk Shirt')+ expect(names).not_to include('Blue Running Shoes', 'Red Cotton Shirt')+ end++ it 'searches text and filters by category' do+ get :index, params: { q: { search: 'blue', categories_id_eq: shoes_category.prefixed_id } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Blue Running Shoes')+ expect(names).not_to include('Blue Silk Shirt', 'Red Cotton Shirt')+ end++ it 'searches text and filters by option value' do+ get :index, params: { q: { search: 'shirt', with_option_value_ids: [red.prefixed_id] } }++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).to include('Red Cotton Shirt')+ expect(names).not_to include('Blue Silk Shirt')+ end+ end++ describe 'visibility' do+ it 'excludes draft products' do+ get :index++ expect(response).to have_http_status(:ok)+ names = json_response['data'].map { |p| p['name'] }+ expect(names).not_to include('Draft Hat')+ end+ end++ describe 'browsing without search query' do+ it 'returns all active products' do+ get :index++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].size).to eq(3)+ end+ end++ describe 'pagination' do+ it 'paginates results' do+ get :index, params: { limit: 2, page: 1 }++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].size).to eq(2)+ expect(json_response['meta']['count']).to be >= 3+ end+ end++ private++ def wait_for_meilisearch_indexing!+ client = ::Meilisearch::Client.new(ENV['MEILISEARCH_URL'])++ # Wait for all tasks to complete (settings + document indexing)+ 100.times do+ tasks = client.tasks(index_uids: [index_name], statuses: ['enqueued', 'processing'])+ break if tasks['results'].empty?++ sleep 0.1+ end++ # Extra wait for filterable attribute indexing to apply+ sleep 0.5+ end+enddiff --git a/spree/common_spree_dependencies.rb b/spree/common_spree_dependencies.rbindex 2bfef1fa17..722579ce25 100644--- a/spree/common_spree_dependencies.rb+++ b/spree/common_spree_dependencies.rb@@ -17,6 +17,8 @@ platforms :ruby dogem 'sqlite3', '>= 2.0'end+gem 'meilisearch', '>= 0.28'+group :test dogem 'parallel_tests'gem 'capybara'diff --git a/spree/core/app/models/spree/search_provider/meilisearch.rb b/spree/core/app/models/spree/search_provider/meilisearch.rbnew file mode 100644index 0000000000..802afa8f49--- /dev/null+++ b/spree/core/app/models/spree/search_provider/meilisearch.rb@@ -0,0 +1,323 @@+module Spree+ module SearchProvider+ class Meilisearch < Base+ PREFIXED_ID_PATTERN = /\A[a-z]+_[A-Za-z0-9]+\z/+ ALLOWED_STATUSES = %w[active draft archived paused].freeze++ def self.indexing_required?+ true+ end++ def initialize(store)+ super+ require 'meilisearch'+ rescue LoadError+ raise LoadError, "Add `gem 'meilisearch'` to your Gemfile to use the Meilisearch search provider"+ end++ def search_and_filter(scope:, query: nil, filters: {}, sort: nil, page: 1, limit: 25)+ page = [page.to_i, 1].max+ limit = limit.to_i.clamp(1, 100)++ search_params = {+ filter: build_filters(filters),+ facets: facet_attributes,+ sort: build_sort(sort),+ offset: (page - 1) * limit,+ limit: limit+ }++ Rails.logger.debug { "[Meilisearch] index=#{index_name} query=#{query.inspect} #{search_params.compact.inspect}" }++ ms_result = client.index(index_name).search(query.to_s, search_params)++ Rails.logger.debug { "[Meilisearch] #{ms_result['estimatedTotalHits']} hits in #{ms_result['processingTimeMs']}ms" }++ prefixed_ids = ms_result['hits'].map { |h| h['prefixed_id'] }+ raw_ids = prefixed_ids.filter_map { |pid| Spree::Product.decode_prefixed_id(pid) }++ # Intersect with AR scope for security/visibility.+ # Since we filter by store/status/currency/discontinue_on in Meilisearch,+ # the AR scope is a safety net — it should not filter anything out.+ products = if raw_ids.any?+ scope.where(id: raw_ids).reorder(nil)+ else+ scope.none+ end++ # Build Pagy object from Meilisearch response (passive mode)+ pagy = build_pagy(ms_result, page, limit)++ SearchResult.new(+ products: products,+ filters: build_facet_response(ms_result['facetDistribution'] || {}),+ sort_options: available_sort_options.map { |id| { id: id } },+ default_sort: 'manual',+ total_count: ms_result['estimatedTotalHits'] || 0,+ pagy: pagy+ )+ end++ def index(product)+ document = ProductPresenter.new(product, store).call+ client.index(index_name).add_documents([document], 'prefixed_id')+ end++ def remove(product)+ client.index(index_name).delete_document(product.prefixed_id)+ rescue ::Meilisearch::ApiError => e+ raise unless e.http_code == 404+ end++ def index_batch(documents)+ client.index(index_name).add_documents(documents, 'prefixed_id')+ end++ # Remove document by prefixed_id (e.g. 'prod_abc')+ def remove_by_id(prefixed_id)+ client.index(index_name).delete_document(prefixed_id)+ rescue ::Meilisearch::ApiError => e+ raise unless e.http_code == 404+ end++ def reindex(scope = nil)+ scope ||= store.products+ ensure_index_settings!++ scope.reorder(id: :asc)+ .preload(:taxons, :option_types, :primary_media,+ variants_including_master: [:prices, :option_values])+ .find_in_batches(batch_size: 500) do |batch|+ documents = batch.map { |product| ProductPresenter.new(product, store).call }+ index_batch(documents)+ end+ end++ # Configure index settings for filtering, sorting, and faceting.+ # Called automatically by reindex, but can be called separately.+ def ensure_index_settings!+ index = client.index(index_name)+ index.update_filterable_attributes(filterable_attributes)+ index.update_sortable_attributes(sortable_attributes)+ index.update_searchable_attributes(searchable_attributes)+ end++ private++ def client+ @client ||= ::Meilisearch::Client.new(+ ENV.fetch('MEILISEARCH_URL', 'http://localhost:7700'),+ ENV['MEILISEARCH_API_KEY']+ )+ end++ def index_name+ "#{store.code}_products"+ end++ def searchable_attributes+ ['name', 'name_*', 'description', 'description_*', 'sku', 'option_values', 'category_names', 'tags']+ end++ def filterable_attributes+ attrs = %w[status in_stock store_ids currency_codes discontinue_on category_ids tags]++ # Price fields per currency: price_USD, price_EUR, etc.+ currencies = store.supported_currencies_list.map(&:iso_code)+ currencies.each { |c| attrs << "price_#{c}" }++ attrs << 'option_value_ids'++ attrs+ end++ def sortable_attributes+ attrs = %w[created_at available_on units_sold_count]++ # Price fields per currency+ currencies = store.supported_currencies_list.map(&:iso_code)+ currencies.each { |c| attrs << "price_#{c}" }++ attrs+ end++ def facet_attributes+ filterable_attributes+ end++ def available_sort_options+ %w[price -price name -name -available_on available_on best_selling]+ end++ # Convert Ransack-style filters to Meilisearch filter syntax.+ # Always applies store scoping, active status, and currency availability+ # so that Meilisearch results match what the AR scope would return.+ # All values are sanitized to prevent filter injection.+ def build_filters(filters)+ conditions = []++ # Always scope to current store and active products with prices in currency.+ # This mirrors the AR scope: store.products.active(currency)+ conditions << "store_ids = '#{store.id}'"+ conditions << "status = 'active'"+ conditions << "currency_codes = '#{currency}'"+ conditions << "(discontinue_on = 0 OR discontinue_on > #{Time.current.to_i})"++ filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)+ return conditions if filters.blank?++ filters.each do |key, value|+ next if value.blank?++ key = key.to_s+ case key+ when 'price_gte'+ conditions << "price_#{currency} >= #{value.to_f}"+ when 'price_lte'+ conditions << "price_#{currency} <= #{value.to_f}"+ when 'in_stock'+ conditions << 'in_stock = true' if value.to_s != '0'+ when 'out_of_stock'+ conditions << 'in_stock = false' if value.to_s != '0'+ when 'categories_id_eq'+ conditions << "category_ids = '#{sanitize_prefixed_id(value)}'" if valid_prefixed_id?(value)+ when 'with_option_value_ids'+ Array(value).each do |ov|+ conditions << "option_value_ids = '#{sanitize_prefixed_id(ov)}'" if valid_prefixed_id?(ov)+ end+ when 'status_eq'+ conditions << "status = '#{value}'" if ALLOWED_STATUSES.include?(value.to_s)+ end+ end++ conditions+ end++ def build_sort(sort)+ return nil if sort.blank?++ case sort+ when 'price'+ ["price_#{currency}:asc"]+ when '-price'+ ["price_#{currency}:desc"]+ when 'name'+ ["name_#{I18n.locale}:asc"]+ when '-name'+ ["name_#{I18n.locale}:desc"]+ when '-available_on'+ ['available_on:desc']+ when 'available_on'+ ['available_on:asc']+ when 'best_selling'+ ['units_sold_count:desc']+ end+ end++ # Transform Meilisearch facetDistribution into our standard filter response format+ def build_facet_response(facet_distribution)+ filters = []++ # Price range+ price_key = "price_#{currency}"+ if facet_distribution[price_key].present?+ amounts = facet_distribution[price_key].keys.map(&:to_f)+ filters << {+ id: 'price',+ type: 'price_range',+ min: amounts.min,+ max: amounts.max,+ currency: currency+ }+ end++ # Availability+ if facet_distribution['in_stock'].present?+ in_stock = facet_distribution['in_stock']['true'] || 0+ out_of_stock = facet_distribution['in_stock']['false'] || 0+ filters << {+ id: 'availability',+ type: 'availability',+ options: [+ { id: 'in_stock', count: in_stock },+ { id: 'out_of_stock', count: out_of_stock }+ ]+ }+ end++ # Option values — group by option type for faceted display+ if facet_distribution['option_value_ids'].present?+ prefixed_ids = facet_distribution['option_value_ids'].keys+ raw_ids = prefixed_ids.filter_map { |pid| Spree::OptionValue.decode_prefixed_id(pid) }+ option_values = Spree::OptionValue.where(id: raw_ids).includes(:option_type).index_by(&:prefixed_id)++ # Group by option type+ by_option_type = {}+ facet_distribution['option_value_ids'].each do |ov_prefixed_id, count|+ ov = option_values[ov_prefixed_id]+ next unless ov++ ot = ov.option_type+ by_option_type[ot] ||= []+ by_option_type[ot] << { id: ov.prefixed_id, name: ov.name, presentation: ov.presentation, position: ov.position, count: count }+ end++ by_option_type.each do |option_type, values|+ filters << {+ id: option_type.prefixed_id,+ type: 'option',+ name: option_type.name,+ presentation: option_type.presentation,+ options: values.sort_by { |o| o[:position] }+ }+ end+ end++ # Categories+ if facet_distribution['category_ids'].present?+ prefixed_ids = facet_distribution['category_ids'].keys+ raw_ids = prefixed_ids.filter_map { |pid| Spree::Taxon.decode_prefixed_id(pid) }+ categories = Spree::Taxon.where(id: raw_ids).index_by(&:prefixed_id)++ filters << {+ id: 'categories',+ type: 'category',+ options: facet_distribution['category_ids'].filter_map do |prefixed_id, count|+ cat = categories[prefixed_id]+ next unless cat++ { id: cat.prefixed_id, name: cat.name, permalink: cat.permalink, count: count }+ end+ }+ end++ filters+ end++ def build_pagy(ms_result, page, limit)+ require 'pagy'+ require 'pagy/toolbox/paginators/meilisearch'++ fake_result = Struct.new(:raw_answer).new({+ 'totalHits' => ms_result['estimatedTotalHits'] || 0,+ 'hitsPerPage' => limit,+ 'page' => page+ })++ Pagy::MeilisearchPaginator.paginate(fake_result, {})+ end++ def currency+ Spree::Current.currency || store.default_currency+ end++ def valid_prefixed_id?(value)+ value.to_s.match?(PREFIXED_ID_PATTERN)+ end++ def sanitize_prefixed_id(value)+ value.to_s.gsub(/[^a-zA-Z0-9_]/, '')+ end+ end+ end+enddiff --git a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rbnew file mode 100644index 0000000000..3eb78307ee--- /dev/null+++ b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb@@ -0,0 +1,201 @@+require 'spec_helper'+require 'meilisearch'++module Spree+ RSpec.describe SearchProvider::Meilisearch do+ let(:store) { @default_store }+ let(:provider) { described_class.new(store) }+ let(:mock_client) { instance_double(::Meilisearch::Client) }+ let(:mock_index) { double('MeiliSearch::Index') }++ let!(:product_1) { create(:product, name: 'Blue Shirt', stores: [store]) }+ let!(:product_2) { create(:product, name: 'Red Pants', stores: [store]) }++ before do+ allow(::Meilisearch::Client).to receive(:new).and_return(mock_client)+ allow(mock_client).to receive(:index).and_return(mock_index)+ end++ describe '#search_and_filter' do+ let(:ms_response) do+ {+ 'hits' => [+ { 'prefixed_id' => product_1.prefixed_id },+ { 'prefixed_id' => product_2.prefixed_id }+ ],+ 'estimatedTotalHits' => 2,+ 'facetDistribution' => {+ 'in_stock' => { 'true' => 2 },+ "price_#{store.default_currency}" => { '19.99' => 1, '29.99' => 1 }+ }+ }+ end++ before do+ allow(mock_index).to receive(:search).and_return(ms_response)+ end++ it 'returns a SearchResult' do+ result = provider.search_and_filter(scope: store.products, query: 'shirt')+ expect(result).to be_a(SearchProvider::SearchResult)+ end++ it 'queries Meilisearch with the search term' do+ expect(mock_index).to receive(:search).with('shirt', hash_including(:limit, :offset))+ provider.search_and_filter(scope: store.products, query: 'shirt')+ end++ it 'returns products from the AR scope matching Meilisearch IDs' do+ result = provider.search_and_filter(scope: store.products, query: 'shirt')+ expect(result.products).to include(product_1, product_2)+ end++ it 'returns total count from Meilisearch' do+ result = provider.search_and_filter(scope: store.products, query: 'shirt')+ expect(result.total_count).to eq(2)+ end++ it 'returns facets from Meilisearch' do+ result = provider.search_and_filter(scope: store.products, query: 'shirt')+ expect(result.filters).to be_an(Array)++ price_filter = result.filters.find { |f| f[:type] == 'price_range' }+ expect(price_filter).to be_present+ expect(price_filter[:min]).to eq(19.99)+ expect(price_filter[:max]).to eq(29.99)+ end++ it 'returns sort options as objects' do+ result = provider.search_and_filter(scope: store.products, query: 'shirt')+ ids = result.sort_options.map { |o| o[:id] }+ expect(ids).to include('price', '-price')+ end++ context 'with no results' do+ let(:ms_response) { { 'hits' => [], 'estimatedTotalHits' => 0, 'facetDistribution' => {} } }++ it 'returns empty relation' do+ result = provider.search_and_filter(scope: store.products, query: 'nonexistent')+ expect(result.products).to be_empty+ expect(result.total_count).to eq(0)+ end+ end++ context 'with price filter' do+ it 'passes price filter to Meilisearch' do+ expect(mock_index).to receive(:search).with(anything, hash_including(+ filter: include("price_#{store.default_currency} >= 10.0")+ )).and_return(ms_response)++ provider.search_and_filter(scope: store.products, filters: { 'price_gte' => '10' })+ end+ end++ context 'with in_stock filter' do+ it 'passes stock filter to Meilisearch' do+ expect(mock_index).to receive(:search).with(anything, hash_including(+ filter: include('in_stock = true')+ )).and_return(ms_response)++ provider.search_and_filter(scope: store.products, filters: { 'in_stock' => '1' })+ end+ end++ context 'with sort' do+ it 'passes price sort to Meilisearch' do+ expect(mock_index).to receive(:search).with(anything, hash_including(+ sort: ["price_#{store.default_currency}:asc"]+ )).and_return(ms_response)++ provider.search_and_filter(scope: store.products, sort: 'price')+ end++ it 'passes descending price sort' do+ expect(mock_index).to receive(:search).with(anything, hash_including(+ sort: ["price_#{store.default_currency}:desc"]+ )).and_return(ms_response)++ provider.search_and_filter(scope: store.products, sort: '-price')+ end+ end++ context 'with pagination' do+ it 'passes offset and limit' do+ expect(mock_index).to receive(:search).with(anything, hash_including(+ offset: 25, limit: 25+ )).and_return(ms_response)++ provider.search_and_filter(scope: store.products, page: 2, limit: 25)+ end+ end++ context 'with visibility scope' do+ it 'intersects Meilisearch results with AR scope' do+ restricted_scope = store.products.where(id: product_1.id)+ result = provider.search_and_filter(scope: restricted_scope, query: 'shirt')+ expect(result.products).to include(product_1)+ expect(result.products).not_to include(product_2)+ end+ end+ end++ describe '#index' do+ it 'adds document to Meilisearch index with prefixed_id as primary key' do+ expect(mock_index).to receive(:add_documents).with(+ [hash_including(prefixed_id: product_1.prefixed_id, name: 'Blue Shirt')],+ 'prefixed_id'+ )+ provider.index(product_1)+ end++ it 'uses ProductPresenter to serialize' do+ presenter = instance_double(SearchProvider::ProductPresenter, call: { prefixed_id: 'prod_abc' })+ allow(SearchProvider::ProductPresenter).to receive(:new).with(product_1, store).and_return(presenter)+ expect(mock_index).to receive(:add_documents).with([{ prefixed_id: 'prod_abc' }], 'prefixed_id')+ provider.index(product_1)+ end+ end++ describe '#remove' do+ it 'deletes document by prefixed_id from Meilisearch index' do+ expect(mock_index).to receive(:delete_document).with(product_1.prefixed_id)+ provider.remove(product_1)+ end+ end++ describe '#remove_by_id' do+ it 'deletes document by prefixed_id' do+ expect(mock_index).to receive(:delete_document).with('prod_abc')+ provider.remove_by_id('prod_abc')+ end++ it 'ignores 404 errors' do+ error = ::Meilisearch::ApiError.new(404, 'not found', 'document_not_found')+ allow(mock_index).to receive(:delete_document).and_raise(error)+ expect { provider.remove_by_id('prod_abc') }.not_to raise_error+ end+ end++ describe '#reindex' do+ before do+ allow(mock_index).to receive(:update_filterable_attributes)+ allow(mock_index).to receive(:update_sortable_attributes)+ allow(mock_index).to receive(:update_searchable_attributes)+ end++ it 'configures index settings' do+ expect(mock_index).to receive(:update_filterable_attributes)+ expect(mock_index).to receive(:update_sortable_attributes)+ expect(mock_index).to receive(:update_searchable_attributes)+ allow(mock_index).to receive(:add_documents)++ provider.reindex(store.products)+ end++ it 'indexes all products in batches' do+ expect(mock_index).to receive(:add_documents).at_least(:once)+ provider.reindex(store.products)+ end+ end+ end+end