Back to Repositories

Testing Default Scope Behavior in Searchkick Integration

This test suite validates the behavior of default scoping in Searchkick, focusing on reindexing and search operations with ActiveRecord models. It ensures proper handling of active/inactive records and verifies search functionality with model scopes.

Test Coverage Overview

The test suite covers essential Searchkick functionality with default scopes, specifically testing reindexing and search operations.

Key areas tested include:
  • Reindexing with active/inactive records
  • Search operations on model vs relations
  • Error handling for incorrect search calls

Implementation Analysis

The testing approach uses Minitest framework with focused unit tests for Searchkick integration. Tests employ a Band model with an active scope, demonstrating proper setup and teardown patterns.

Implementation highlights:
  • Setup method clearing test data
  • Store helper method for test data creation
  • Assertion patterns for search results and errors

Technical Details

Testing infrastructure includes:
  • Minitest as the testing framework
  • Searchkick integration for search functionality
  • ActiveRecord for data persistence
  • Custom test helper methods for data setup
  • Assert/raise patterns for validation

Best Practices Demonstrated

The test suite demonstrates several testing best practices for search functionality.

Notable practices include:
  • Proper test isolation with setup methods
  • Explicit error case testing
  • Clear test method naming
  • Focused test scenarios
  • Proper assertion messaging

ankane/searchkick

test/default_scope_test.rb

            
require_relative "test_helper"

class DefaultScopeTest < Minitest::Test
  def setup
    Band.destroy_all
  end

  def test_reindex
    store [
      {name: "Test", active: true},
      {name: "Test 2", active: false}
    ], reindex: false

    Band.reindex
    assert_search "*", ["Test"], {load: false}
  end

  def test_search
    Band.reindex
    Band.search("*") # test works

    error = assert_raises(Searchkick::Error) do
      Band.all.search("*")
    end
    assert_equal "search must be called on model, not relation", error.message
  end

  def default_model
    Band
  end
end