require_relative 'setup' # # Hstore - Since 8.4 # # A hash of strings. # # http://www.postgresql.org/docs/9.4/static/hstore.html # class Post < ActiveRecord::Base end describe "hstore" do before(:all) do ActiveRecord::Schema.define do #execute "CREATE EXTENSION IF NOT EXISTS hstore" create_table :posts, force: true do |t| t.string :title t.hstore :properties end end Post.reset_column_information end before { Post.delete_all } let!(:tdd) { Post.create!(title: "TDD is dead", properties: { author: "DHH", word_count: 100 }).reload } let!(:bdd) { Post.create!(title: "BDD is woot", properties: { author: "Philippe", word_count: 42 }).reload } let!(:foo) { Post.create!(title: "FOO is bar", properties: { author: "Philippe", draft: true }).reload } it "converts keys and values to strings" do expect(tdd.properties).to eq("author" => "DHH", "word_count" => "100") expect(bdd.properties).to eq("author" => "Philippe", "word_count" => "42") expect(foo.properties).to eq("author" => "Philippe", "draft" => "true") end it "saves when an element is changed" do tdd.properties["author"] = "Bob" tdd.save! tdd.reload expect(tdd.properties).to eq("author" => "Bob", "word_count" => "100") end it "searches for records with key" do results = Post.where("properties ? :key", key: "draft") expect(results).to eq [foo] end it "searches for records with specific property" do results = Post.where("properties -> :key = :value", key: "author", value: "Philippe") expect(results).to eq [bdd, foo] end it "searches for records with specific a value that we like" do results = Post.where("properties -> :key LIKE :value", key: "author", value: "Phil%") expect(results).to eq [bdd, foo] end end