3

Is there a way to test if a database index exists with RSpec?

I'm using friendly_id gem and often I forget to create the database index for slug field. So, I would like to include this in my RSpec tests.

2
  • Yes, check out shoulda gem Commented Sep 12, 2014 at 12:56
  • I'm already using shoulda-matchers. But did not find the matcher that I need. Commented Sep 12, 2014 at 12:59

1 Answer 1

5

You can use index_exists? check unique by options unique: true:

=> ActiveRecord::Migration.index_exists?(:users, :user_id, unique: true)
=> -- index_exists?(:users, :user_id)
=>   -> 0.0559s
=> false

or:

=> ActiveRecord::Base.connection.index_exists?(:users, :user_id)
=> false

or based on should-matchers:

=> ActiveRecord::Base.connection.indexes(:users).map(&:columns)
=> [["birthday"],
=> ["confirmation_token"],
=> ["email"],
=> ["facebook_id"],
=> ["reset_password_token"]]

with unique:

=>ActiveRecord::Base.connection.indexes(:users).map { |x| Hash[:unique, x.unique, :column, x.columns ] }
=> [{:unique=>false, :column=>["birthday"]},
=> {:unique=>true, :column=>["confirmation_token"]},
=> {:unique=>true, :column=>["email"]},
=> {:unique=>true, :column=>["facebook_id"]},
=> {:unique=>true, :column=>["reset_password_token"]}]
Sign up to request clarification or add additional context in comments.

1 Comment

Will be best to test the query that is supposed to use the index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.