🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
Framework integration / Rails / Advanced

Raise or log exceptions

By default, this gem raises exceptions if something goes wrong. You can control this with the raise_on_failure option. If set to false, all exceptions are logged.

1
2
3
4
5
6
7
8
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  # Only raise exceptions if not in a production environment
  algoliasearch raise_on_failure: !Rails.env.production? do
    attribute :first_name, :last_name, :email
  end
end

Turn off indexing

Use the following code snippet to turn off indexing based on the current Rails environment. This can be helpful during testing or development.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch disable_indexing: Rails.env.test? do
    # Algolia configuration
  end
end

class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch disable_indexing: Proc.new { Rails.env.test? || more_complex_condition } do
    # Algolia configuration
  end
end

Wait for indexing tasks

Indexing operations are asynchronous by default. During your tests, you might create models and then confirm if they were indexed in Algolia. To test this, it’s best to make your indexing synchronous.

1
2
3
4
5
6
7
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch synchronous: Rails.env.test? do
    # Algolia configuration
  end
end

This option should only be used for testing purposes.

Mock the Algolia API

To mock your API calls to the Algolia API, use the MockRequester class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
describe 'With a mocked client' do

  before(:all) do
    mock_requester = MockRequester.new
    mock_client = Algolia::Search::Client.new(
      Algolia::Search::Config.new(AlgoliaSearch.configuration),
      http_requester: mock_requester
    )

    # Override the client
    AlgoliaSearch.instance_variable_set(:@client, mock_client)
  end

  it "shouldn't perform any API calls here" do
    User.create(name: 'My Indexed User')  # mocked, no API call performed
    User.search('').should == {}          # mocked, no API call performed
  end
end

Run tests for the Algolia Search gem

If you want to contribute to this gem, you can run the tests locally or let the CI run them when opening your pull requests.

Before you run the tests, set the ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY environment variables. Since the tests create and delete indices, make sure the index names won’t affect your production.

Did you find this page helpful?