Integrations / Frameworks / Rails / Developing & Testing

Developing & Testing

Raising or logging Exceptions

By default, this gem will raise exceptions if something goes wrong. You can turn this on and off via the raise_on_failure option. If raising is turned off, all exceptions will be logged.

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

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

Disabling indexing

A simple way to turn off indexing based on the Rails environment. The following snippet will disable all indexing (add, update & delete operations) API calls when running tests.

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

Making Algolia synchronous

Every time you send an indexing operation to Algolia, the API returns a taskID and will process your operation asynchronously. The Algolia API client provides an easy way to wait until an operation is completed via the wait_task method.

In your test, you may create models and then search for them to confirm they were indexed in Algolia. The best way to achieve that is to wait after every operation. This gems makes it easy to turn every indexing operation synchronous via the :synchronous option key.

This option should only be used for testing purposes.

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

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

Mocking

Another way to run your test with Algolia is to mock Algolia’s API calls. We provide a WebMock sample configuration that you can use including algolia/webmock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
require 'algolia/webmock'

describe 'With a mocked client' do

  before(:each) do
    WebMock.enable!
  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

  after(:each) do
    WebMock.disable!
  end

end

Running test on this gem

If you plan to contribute to this gem, you can run the test locally or let Travis run them when opening your PR.

To run the specs, please set the ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY environment variables. Since the tests are creating and removing indices, make sure the index names won’t affect your production.

Did you find this page helpful?